Why did this not print an assert error?
This is my code:
#include<assert.h>
#include<stdio.h>
int main(){
int n =12;
char str[50] = "";
assert(n>=10);
printf("output :%d\n",n);
assert(str!=NULL);
printf("output :%s\n",str);
}
CodePudding user response:
char str[50] = "";
This makes str
into an array of 50 chars, and initialises the memory to all zeroes (first byte explicitly from ""
and rest implicitly, because C does not support partial initialisation of arrays or structs).
assert(str!=NULL);
When used in an expression, array is treated as pointer to its first element. The first element of the array very much has an address, so it is not NULL
.
If you want to test if the first element of the array is 0, meaning empty string you need
assert(str[0] != '\0');
You could compare to 0
, or just say assert(*str);
, but comparing to character literal '\0'
makes it explicit to the reader of the code, that you are probably testing for string-terminating zero byte, not some other kind of zero, even if for the C compiler they're all the same.
CodePudding user response:
str is an array which is effectively a pointer, which means the address in memory where the array is stored. A pointer is NULL if it doesn't point to any specific place in memory. Your str pointer is not null, it points to a place in memory containing an array of 50 elements.
That array is an array of chars, otherwise known as a string. You initialise it to an empty string but it's still there and the pointer to it (str) is still a valid, non-NULL pointer.
str!=NULL does not mean "str is not an empty string"! It means "str is not an undefined pointer".