当我尝试循环执行以下 C 程序时,出现错误:“Segmentation fault: 11”
#include <stdio.h>
main() {
int i;
char *a[] = {
"hello",
"how are you",
"what is your name"
};
for (i = 0; a[i][0] != '\0'; i++ ) {
printf("\n%s", a[i]);
}
}
但是当我用以下代码替换 for
循环中的测试时,我没有收到错误并且一切正常。
for (i = 0; i < 3; i++ ) {
printf("\n%s", a[i]);
}
如果有人能向我解释为什么测试 a[i][0] != '\0'
不起作用,以及我应该怎么做,我将不胜感激.
最佳答案
您需要缺少一个终止字符串。您对 a
的定义应该是
char *a[] = {
"hello",
"how are you",
"what is your name",
""
};
如果没有空字符串,您将访问不存在的 a[3]
,因此会出现段错误。
关于C - 遍历指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17266244/