开发者

Is it wrong to terminate a c-string with 0 instead of '\0'?

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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜