I have a char array and I want to check if it is null.
if(_char_array[0] != '\0') {...}
is the same as
if(_char_array != '\0') {...}
thanks
CodePudding user response:
This if statement
if(_char_array[0] != '\0') {...}
checks whether a character array contains a non-empty string.
In fact there are compared two integers: the first character of the array _char_array
promoted to the type int
and the integer character constant '\0'
that has the type int
.
This if statement
if(_char_array != '\0') {...}
does not make a sense because any array occupies a memory extent. So converted to a pointer to its first element it can not be a null pointer.
That is in this statement there are compared a pointer to the first element of the array due to the implicit conversion of the array to a pointer to its first element and a null pointer constant.
If _char_array
is initially declared as a pointer then the above if statement checks whether the pointer is not a null pointer.
CodePudding user response:
An array name is not a pointer, but an identifier for a variable of type array, which is implicitly converted to a pointer to the element type. These two are not the same at all, the array will always have value.
CodePudding user response:
In the first if
statement you were checking whether the first element of _char_array
is 0
or not, whereas in the second if
statement you were checking address of _char_array
to be 0
or not.
If the address is 0
then there would be 2 cases:
CASE 1
char *_char_array = NULL;
CASE 2
char *_char_array = malloc(<any_size>); // but malloc failed and returned `NULL`
NOTE: Statically allocated arrays never have an address of 0
.