据我所知,字符串被CUL中的NUL '\0'
字节终止。然而,我不明白为什么0
在字符串文字中的行为不同于0
在堆栈中创建的char数组中。当在文字中检查NUL终止符时,数组中间的零不会被视为这样。NUL字符和静态字符数组/字符串在C
例如:
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
int main()
{
/* here, one would expect strlen to evaluate to 2 */
char *confusion = "11001";
size_t len = strlen(confusion);
printf("length = %zu\n", len); /* why is this == 5, as opposed to 2? */
/* why is the entire segment printed here, instead of the first two bytes?*/
char *p = confusion;
while (*p != '\0')
putchar(*p++);
putchar('\n');
/* this evaluates to true ... OK */
if ((char)0 == '\0')
printf("is null\n");
/* and if we do this ... */
char s[6];
s[0] = 1;
s[1] = 1;
s[2] = 0;
s[3] = 0;
s[4] = 1;
s[5] = '\0';
len = strlen(s); /* len == 2, as expected. */
printf("length = %zu\n", len);
return 0;
}
输出:
length = 5
11001
is null
length = 2
为什么会发生这种情况?
字符串文字** **是一个'char'阵! C语言中没有堆栈。而指针不是一个数组。 “在这里,人们会希望strlen评价为2” - 为什么?看起来好像对数组,指针和字符串有一些误解。 – Olaf
因为'0'!= 0 – John3136
字符'0'的值为48([通常](https://en.wikipedia.org/wiki/EBCDIC))。空终止符“'\ 0''的值为零。 –