[英]Accessing first element of string array in C
這可能是一個新手問題,但這是我的問題:
我想聲明一個字符串數組,但是當我訪問第一個元素時,其他元素會與它連接起來。
#include <stdio.h>
int main(){
char words[2][3] = {"foo", "bar"};
printf("%s\n", words[0]); // I want to print foo
printf("%s\n", words[1]); // I want to print bar
}
哪個輸出
foobar
bar
雖然我在期待
foo
bar
有人能解釋一下:
您的數組word
沒有足夠的空間用於字符串末尾的空字節,當您嘗試將元素打印為C字符串時(使用%s
),它會導致未定義的行為 。 增加數組大小:
char words[2][4] = {"foo", "bar"};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.