C
Christian Kandeler
Hi,
if I want to store the string "123456" in a variable of type char[], I can
do it like this:
char s[] = "123456";
Or like this:
char s[] = { '1', '2', '3', '4', '5', '6', '\0' };
Or like this:
char s[7] = "123456";
These are all equivalent because string literals have an implicit '\0'
character at the end. That's why it is a mistake to write this:
char s[6] = "123456";
Here we reserve one byte less than we need. Now here's my question: Doesn't
that mistake warrant a diagnostic? I was quite baffled today when four
different compilers failed to generate even a warning when fed the above
code, even though the mistake should be easy to detect. Or am I
misunderstanding string literals?
Thanks,
Christian
if I want to store the string "123456" in a variable of type char[], I can
do it like this:
char s[] = "123456";
Or like this:
char s[] = { '1', '2', '3', '4', '5', '6', '\0' };
Or like this:
char s[7] = "123456";
These are all equivalent because string literals have an implicit '\0'
character at the end. That's why it is a mistake to write this:
char s[6] = "123456";
Here we reserve one byte less than we need. Now here's my question: Doesn't
that mistake warrant a diagnostic? I was quite baffled today when four
different compilers failed to generate even a warning when fed the above
code, even though the mistake should be easy to detect. Or am I
misunderstanding string literals?
Thanks,
Christian