When to use NULL and when to use '\ 0' in a linked list in C?

I found out in C: null char == '\0' == NULLand I wrote a loop below to read from beginning to end char [] in C.

// case #1
char buf[32];
while (buf[i] != NULL){
    //do something...
}  

However, my gcc compiler gave me a warning: a comparison between a pointer and an integer. Someone said that I misled two separate concepts: NULL for pointers, while "\ 0" for characters. Therefore, to get rid of the warning, I have to use '\ 0', since my loop checks for char.

Now I am writing a linked list and checking if the pointer points to the head of the node or not. Since it is structured, it is reasonable to use if (h1 == NULL), but apparently the compiler also compiles when I use if (h1 == '\0'), although node is a structure but not a char. Can someone help why both "\ 0" and NULL can be used in this case, until they can be used as in the first case?

// case #2
struct ListNode {
    int val;
    struct ListNode *next;
};
+4
source share
3 answers

. " " ( NUL, L, ) , . " " - , . - , . , , , .

C , , . , : 0 , NULL '\0'. , #define NULL 0 C. - , (T*)0 T, 0, NULL, , , (, execl).

, C int, char, '\0' - . ( ++ .)

โ€‹โ€‹C, IMNSHO '\0' , 0 - not NULL - .

+7

NULL :

#define NULL ((char *)0)

#define NULL ((void *)0)

#define NULL 0L

#define NULL 0

NULL . 0 , , ListNode* 0 ( NULL , - ):

if (h1 == 0)

:

if (!h1)

A '\0' int C int ++. , '\0' .

'\0' ( 0) , NULL:

while (buf[i] != '\0') // or 0

:

while (buf[i])
+3

NULL . '\0' (.. char)

If you had an array of structures, you may need to iterate over them until you reach the end:

MyStruct** things = ...
for(int i = 0; things[i] != NULL; i++) {
    // Do something with things[i]
}

This loop ends when the pointer to the last structure NULL.

+1
source

Source: https://habr.com/ru/post/1608234/


All Articles