2017-04-13 85 views
-2

據我所知,字符串被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 

爲什麼會發生這種情況?

+0

字符串文字** **是一個'char'陣! C語言中沒有堆棧。而指針不是一個數組。 「在這裏,人們會希望strlen評價爲2」 - 爲什麼?看起來好像對數組,指針和字符串有一些誤解。 – Olaf

+2

因爲'0'!= 0 – John3136

+1

字符'0'的值爲48([通常](https://en.wikipedia.org/wiki/EBCDIC))。空終止符「'\ 0''的值爲零。 –

回答

1

變量「混亂」是指向一個文本字符串的字符。 所以內存看起來像

[11001\0] 

所以,當你打印變量「混亂」,將打印的一切,直到它由\ 0表示第一個空字符。
11001中的零不爲空,因爲它被雙引號包圍,所以它們幾乎爲零。

但是,在變量's'的char數組賦值中,您正在爲0到 char變量賦值十進制值。當你這樣做時,ASCII字符值爲NULL字符的ASCII十進制值0被分配給它。所以字符數組看起來像在存儲

[happyface, happyface, NULL] 

ASCII字符happyface有1 ASCII十進制值所以,當您打印時,它會照常進行到第NULL,因此 strlen的是2。

這裏的訣竅是理解當給它分配一個十進制值時真正賦予一個字符變量的是什麼。

試試這個代碼:

#include <stdio.h> 

int 
main(void) 
{ 
    char c = 0; 

    printf("%c\n", c); //Prints the ASCII character which is NULL. 
    printf("%d\n", c); //Prints the decimal value. 

    return 0; 

}

0

'0'和0不是相同的值。 (第一個是48,通常,儘管技術上精確的值是實現定義的,並且寫入48來指代字符'0'被認爲是非常糟糕的樣式。)

如果'0'終止了字符字符串,你不能把零置於字符串中,這會有點......限制。