據我所知,字符串被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''的值爲零。 –