簡體   English   中英

這兩個arrays有什么區別?

[英]What is the difference between this two arrays?

它們之間有什么區別? 它們在運行時顯示不同的值。 謝謝。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char good1[] = {'g','o','o','d'};
    char good2[] = {'g','o','o','d','\0'};
    printf("%s %s", good1,good2);

    return 0;
}

\0用於指示字符串中的終止字符。

good1沒有終止字符,因此當顯示 good1 時,您可能會得到一些不需要的字符。 這取決於您使用的編譯器。 結果可能因不同的編譯器而異。

例如,

我在不同的編譯器中執行了上面的代碼。 通過使用 GCC-TDM C 編譯器,output 是

good: good: [我在代碼中添加了':'來知道字符串的結尾]。

在 paiza.io 在線 c 編譯器網站中,output 是

good�K��: good:

同樣,在不同的編譯器輸出可能會有所不同。

而對於good2 ,由於數組末尾有終止字符,因此 output 將符合預期。

嘗試使用\0你會明白其中的區別。

就像在數組中間保留\0並查看 output。 參考這個

https://en.m.wikipedia.org/wiki/Null-terminated_string

希望這可以幫助。

謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM