+ 7

How are NULL and '\0' defined in C?

Are 0, NULL and '\0' one and the same thing? If not, what is the difference and how are they defined?

6th Mar 2019, 9:15 AM
Abhishek Tandon
Abhishek Tandon - avatar
7 Antworten
+ 9
I think that depends on what "are they the same thing" means... If 0 is an integer and '\0' is a char, they won't have the same binary representation because an int takes up (usually) four times the space as a char. If you define char n = 0; char c = '\0'; then n and c might actually have the same binary representation (00000000). However if you compare int n = 0 (which looks like 00000000 00000000 00000000 00000000) and char c = '\0' (which looks like 00000000), they will still be considered equal because the smaller data type (char) gets "upgraded" to an integer to be able to compare them. NULL as in a null pointer might point to the fictional memory address 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 (8 bytes), but I'm not sure about that. Maybe it depends on the implementation. However since you can't dereference a null pointer, there's no way to compare if its value is equal to int 0 or char '\0' (I guess). It doesn't point to a "real" location, so it doesn't have a value (at least not a value you can access).
6th Mar 2019, 11:11 AM
Anna
Anna - avatar
+ 5
Théophile So should I conclude that they both "seem" to be equal to 0, though differ in their binary representation (or specifically '\0' is type casted as well) as pointed out by Anna ? https://code.sololearn.com/cZ08xrLmJ45r/?ref=app
6th Mar 2019, 12:40 PM
Abhishek Tandon
Abhishek Tandon - avatar
+ 3
I don't really know. But when you declare a non initialized pointer, you can do : int *a = NULL; OR int *a(0); And in an array of char, you can do : char a[3] = {97, 98, 0} Or char a[3] = {'a', 'b', '\0'} So I think that are the same...
6th Mar 2019, 10:31 AM
Théophile
Théophile - avatar
+ 3
@theophile yeah that's right 😅
6th Mar 2019, 12:33 PM
Abhishek Tandon
Abhishek Tandon - avatar
+ 2
That's it : in all cases, it's equal to zero, but as said Anna, their binary values are different (sizeof(int) = 4, sizeof(char) = 1).
6th Mar 2019, 3:07 PM
Théophile
Théophile - avatar
+ 1
You're welcome!
6th Mar 2019, 12:35 PM
Théophile
Théophile - avatar
0
No, it is wrong : in your code, you print the address of a, not the address pointed by a!
6th Mar 2019, 12:31 PM
Théophile
Théophile - avatar