I have the following C code:
我有以下C代码:
char hello[14] = "Hello, World!\n
I have the following C code:
我有以下C代码:
char hello[14] = "Hello, World!\n\0";
printf("strlen(\"Hello, World!\") = %d\n", strlen(&hello[0]));
This results in:
这导致:
strlen("Hello, World!") = 40
However if I change my code to:
但是,如果我将我的代码更改为:
char hello[] = "Hello, World!\n\0";
printf("strlen(\"Hello, World!\") = %d\n", strlen(&hello[0]));
I get the correct value of 14.
我得到14的正确值。
When I don't explicitly tell the compiler how many bytes the string takes up it gives me an incorrect strlen value and seems to not null terminate the string.
当我没有明确告诉编译器字符串占用了多少字节时,它给了我一个不正确的strlen值,并且似乎不为null终止字符串。
I have found answers of people having similar problems but not a good explanation of why.
我找到了有类似问题的人的答案,但没有很好地解释原因。
If anyone could explain this to me it'd be appreciated.
如果有人能向我解释这一点,我们将不胜感激。
2 个解决方案
#1
3
This code is a constraint violation:
此代码是违反约束:
char hello[14] = "Hello, World!\n\0";
There are 15 characters inside the quote marks but the array is only size 14. It is excess initializers for aggregate.
引号内有15个字符,但数组只有14号。它是聚合的多余初始值。
So the results of any executable are completely undefined. The compiler should give a diagnostic message.
所以任何可执行文件的结果都是完全未定义的。编译器应该给出诊断消息。
#2
2
char hello[14] = "Hello, World!\n\0";
should be
char hello[] = "Hello, World!\n";
Your string can't fit into 14 characters.
您的字符串不能容纳14个字符。
Array out of bound access can lead to undefined behavior.
数组越界访问可能导致未定义的行为。
No need of explicitly adding a nul character at the end of the string as character array will do it implicitly but you should have space for it.
不需要在字符串的末尾显式添加一个空字符,因为字符数组会隐式地执行它,但你应该有空间。
";
printf("strlen(\"Hello, World!\") = %d\n", strlen(&hello[0]));
char