Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of char* should end at '\0' or "\0"?

Tags:

c

null

pointers

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?

like image 675
Andrew-Dufresne Avatar asked Sep 27 '09 10:09

Andrew-Dufresne


People also ask

How do you end a character array?

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.

Is char * Always null-terminated?

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.

What is the use of \0 in array?

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.

Why we use '\ 0 at the end of the string?

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.


1 Answers

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.

like image 109
Chris Lutz Avatar answered Oct 05 '22 03:10

Chris Lutz