C - 遍历指针数组

标签 c

当我尝试循环执行以下 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/

相关文章:

c - fopen中的r和rb有什么区别

c - 读取未格式化文件的 Fortran 到 C 的翻译

c - 如何返回二维数组?

c - 为什么它等于数组中的第一个整数?

c - RSA 加密的 OpenSSL 可变长度结果 [C 编程]

C - 当输入不是 int 时提示用户输入有效 int 会导致无限循环

c - 为什么这个c程序输出4?

比较非空终止字符数组

c - alloca有什么应用?

c - 如何高效地获取一个数字的最后两位数字?