這個問題在這里已經有了答案: 字符陣列應該如何用作字串? (4 個回答) 12 小時前關閉。
我正在嘗試練習宣告字串,但沒有得到正確的輸出。
#include <stdio.h> //Im using vscode and gcc
int main()
{
char k[]= "prac c";
char l[6]= "stop c"; //first initializing as size 6
char m[6]= "nice c";
printf("%s \n%s \n%s",k,l,m);
return 0;
}
output: prac c
stop cprac c
nice cstop cprac c
但是當我將大小從 6 更改為 7 時,這不會發生。
#include <stdio.h>
int main()
{
char k[]= "prac c";
char l[7]= "stop c"; //changing size to 7
char m[7]= "nice c"; //changing size to 7
printf("%s \n%s \n%s",k,l,m);
return 0;
}
output: prac c
stop c
nice c
uj5u.com熱心網友回復:
該字串"stop c"實際上有七個字符長,包括結尾的空終止符。這適用于您的所有字串。
如果陣列中沒有用于終止符的空間,則不會添加它,并且陣列不再是通常所說的字串。
使用這樣的陣列作為字串將導致代碼超出陣列的范圍并給你未定義的行為。
uj5u.com熱心網友回復:
"prac c", "stop c", "nice c"所有都分別占用 7 個位元組,因為\0字串文字有一個終止符。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/346725.html
上一篇:在postgresql中決議字串
下一篇:從字串訪問文本
