tags:

views:

156

answers:

2

C-strings are null-terminated which means that in a char-array, the char at index strlen() is a byte with all bits set to 0. I've seen code where, instead of '\0', the integer 0 is used. But since sizeof(int) > sizeof(char), this might actually write beyond the allocated space for the array - am I wrong? Or does the compiler implicitely cast a an int to char in such a situation?

+10  A: 

Yes you are wrong - the zero value will be truncated. After all, if you write:

char c = 0;

you would not expect the compiler to write beyond the bounds of the variable c, I hope. If you write something like this:

char c = 12345;

then the compiler should warn you of the truncation. GCC produces:

c.c:2: warning: overflow in implicit constant conversion

but still nothing will be written beyond the bounds of the variable.

anon
+13  A: 

When storing the value 0 in an array of chars, then the int will be implicitly converted to char.

Actually, the type of '\0' is int (contrary to what one may expect), so somechararray[x]=0 and somechararray[x]='\0' are semantically equivalent.

Personally, I prefer to go with '\0', to make it more clear that I'm dealing with a string.

Hans W