2010-12-09 114 views
8

以下哪項是空終止字符串?空終止字符串

char *str1 = "This is a string."; 
char *str2 = "This is a string.\0"; 
char str3[] = "This is a string."; 
const char *str4 = "This is a string."; 
const char *str5 = "This is a string.\0"; 
const char str6[] = "This is a string."; 
+5

「我總是空終止。」 – 2010-12-09 08:07:59

回答

10
  • 所有:一個字符串是一個空值終止字符串
  • str2str5有被雙空值終止

而且特殊性:

  • char *str1應be const char *str1
  • char *str2應該是const char *str2
+2

你對最後一個(str3)錯了。這是一個有效的數組初始化。 – ybungalobill 2010-12-09 07:55:02

8

它們都是空值終止(str2str5實際上是雙空值終止),因爲使用了雙引號是一個空終止字符數組的簡寫。

所以這個:

"Hello" 

其實這是:指向字符串文字如這些

{'H', 'e', 'l', 'l', 'o', '\0'} 

變量應被聲明爲const

1

全部。 C編譯器自動將終止'\ 0'的字符串聚合,然後將其存儲在char []中或通過char *引用它。

-3

不要在使用的情況下,你char*s="hi"如果想你想連接東西,它做的字符串類似修改它,甚至因爲這裏串hi是隻讀存儲器的部分,你的程序會崩潰