[英]Accessing first element of string array in C
It might be a newbie question but here is my problem: 这可能是一个新手问题,但这是我的问题:
I want to declare an array of strings but when I access the first element, the other elements gets concatenated with it. 我想声明一个字符串数组,但是当我访问第一个元素时,其他元素会与它连接起来。
#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
}
Which outputs 哪个输出
foobar
bar
although I was expecting 虽然我在期待
foo
bar
Can someone explain: 有人能解释一下:
Your array word
doesn't have sufficient space for the null bytes at the ends of the strings and it results in undefined behaviour as you attempt to print the elements as C-string (using %s
). 您的数组word
没有足够的空间用于字符串末尾的空字节,当您尝试将元素打印为C字符串时(使用%s
),它会导致未定义的行为 。 Increase the array size: 增加数组大小:
char words[2][4] = {"foo", "bar"};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.