Do you know the difference between "NULL" and "\0"?
As the title says, do you know the difference between NULL
and "\0
?
The both indeed stand for "null", but there is a significant difference. Today I will explain the difference.
About NULL
As you know, the NULL
in C/C++ means that pointer does not point to a valid memory address. To be detailed, the NULL
in C/C++ is a macro defined in many standard libraries such as <stdio.h>
and <stddef.h>
. It represents a null pointer constant, which is a special value used to indicate that a pointer does not point to a valid memory address.
The specific definition of NULL
can vary depending on the compiler and the C standard. However, it is commonly defined as either ((void *)0)
or 0
. In either case, NULL
is a pointer value that points to the memory address 0.
NULL
is used like this:
#include <stddef.h>
int main() {
int *ptr1 = NULL;
char *ptr2 = NULL;
// some code
// ...
}
As the code above shows, NULL
can be used for any kind of pointer variable. NULL
is typically defined as ((void *)0)
, as I mentioned above, which is a void pointer variable. In C/C++, void pointer variables can be converted to other pointer types both implicitly and explicitly. Therefore, if the code above is modified for explicit casting, it can be like:
#include <stddef.h>
int main() {
// explicit casting of NULL
// this syntax is not common in this case
int *ptr1 = (int *)NULL;
char *ptr2 = (char *)NULL;
// some code
// ...
}
In conclusion, NULL
is a special macro used with pointer types to represent a null pointer constant; it is not used with non-pointer types.
About \0
On the other hand, \0
is NOT a pointer, rather it is actually a special value in the type char
. In the type char
of C/C++, every string (array of characters) is terminated with \0
, which indicates the end of the string. Therefore, \0
is indeed called "null", but it is different from NULL
. While NULL
is a macro that represents a null pointer constant, \0
is a character value known as the "null character" or "null terminator".
The difference
See the example below:
#include <stddef.h>
int main() {
char *str1 = "\0";
char *str2 = NULL;
// some code
// ...
}
In this case, str1
is defined as "\0"
, which means str1
is an empty string. The pointer str1
points to the memory address where this empty string is stored.
On the other hand, str2
is defined as NULL
, which means str2
is a pointer variable that is stored in memory somewhere and its value is a special one called the "null pointer constant". The "null pointer constant" is symbolic value that indicates the absence of a valid pointer target. It does not represent a valid memory address that can be dereferenced or accessed like a regular variable.