Lets say we have an array of char pointers
char* array[] = { "abc", "def" };
Now what should be put in the end ?
char* array[] = { "abc", "def", '\0' };
or
char* array[] = { "abc", "def", "\0" };
Though, both works. We only have to put the condition to check the end accordingly
like
array[ index ] != '\0';
or
array[ index ] != "\0";
My question is which one is the better way? Which is used by most programmers?
Edit
Most answers say that NULL is better than '\0' and "\0". But I always thought that
NULL is same as '\0' which is same as 0x0 or 0
Is it wrong?
the null character is used for the termination of array. it is at the end of the array and shows that the array is end at that point. the array automatically make last character as null character so that the compiler can easily understand that the array is ended.
char arrays are not automatically NULL terminated, only string literals, e.g. char *myArr = "string literal"; , and some string char pointers returned from stdlib string methods.
There is nothing "special" about terminating with 0 or \0 . Terminate with whatever works for your case. I think INT_MIN and INT_MAX are the macro names you're after. The array can also contain negative numbers.
What does the \0 symbol mean in a C string? It's the "end" of a string. A null character. In memory, it's actually a Zero.
I would end it with NULL
. Why? Because you can't do either of these:
array[index] == '\0'
array[index] == "\0"
The first one is comparing a char *
to a char
, which is not what you want. You would have to do this:
array[index][0] == '\0'
The second one doesn't even work. You're comparing a char *
to a char *
, yes, but this comparison is meaningless. It passes if the two pointers point to the same piece of memory. You can't use ==
to compare two strings, you have to use the strcmp()
function, because C has no built-in support for strings outside of a few (and I mean few) syntactic niceties. Whereas the following:
array[index] == NULL
Works just fine and conveys your point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With