Home > OS >  how to distinguish between 0 and NULL in C
how to distinguish between 0 and NULL in C

Time:02-20

I am trying to print some integer data which includes the integer 0, but I want to ignore the data containing NULL and not print it. but my C code can't distinguish between 0 and NULL and treats them as if they are the same.

void ecrire(struct node *p) {
    if (p->data == NULL) {   'if the first node contains NULL it means list is empty'
        printf("no items!\n");
        return;
    }
    struct node *temp = p;
    while (temp != NULL) {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n");
}

when I pass a list containing the value 0 in the first node it treats it as if it's an empty list. any solution Please?

CodePudding user response:

The C standard does not provide for an integer type to represent any values other than integers. There is no null or “NULL” value that means “not any integer value.”

The macro NULL is intended for use with pointers, not integers. It is a null pointer constant. For pointers, NULL is a value used to indicate the pointer is not pointing at any thing (some object or function). It should not be used with integers. You could use NULL with the pointer p to determine whether it points to a structure or not, and you could use it with p->next to determine whether there is another node linked to the structure.

If the structure may or may not contain data, then generally you should create another member of the structure that indicates whether or not it contains data (and/or possibly how much data or what type of data). Alternatively, you can designate some integer value representable in the type of the data member that you will never use for its integer value to be an indicator that there is no data present in the structure.

CodePudding user response:

There is a confusion between testing if the pointer to struct node passed to the function is a null pointer and the value of the integer data member of the nodes in the list it points to.

NULL is used in C as a macro to express a null pointer constant. It is used to test for null pointers. 0 is also a null pointer constant in a pointer context. Unlike in SQL, there is no concept of a null value representing no value in C for numeric values.

Here is a modified version of your code:

void ecrire(struct node *p) {
    if (p == NULL) { // if the node pointer is NULL it means list is empty
        printf("no items!\n");
        return;
    }
    struct node *temp = p;
    while (temp != NULL) {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n");
}
  •  Tags:  
  • c
  • Related