这可能是微不足道的,我希望有人能解释一下。为什么 strlen 给我的数字比 char 数组的实际大小更大,而不是 4:这是我的代码:
#include <stdio.h>
#include <string.h>
int main ()
{
char szInput[4];
szInput [0] = '1';
szInput [1] = '1';
szInput [2] = '1';
szInput [3] = '1';
printf ("The sentence entered is %u characters long.\n",(unsigned)strlen(szInput));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我以为我应该得到 4 作为输出,但我得到了 6。
输入的句子长度为 6 个字符。
strlen'\0'仅当字符数组中存在空终止符时才有效。(它返回最多但不包括该终止符的字符数)。
如果不存在,则程序行为未定义。您能得到答案完全是巧合。
如果你已经写了szInput[3] = '\0';,那么你的程序将被明确定义,答案将是 3。你可以写,szInput[3] = 0;但'\0'在处理文字时,为了清晰(和约定),通常更喜欢写char。