关于char的指针数组

时间:2015-09-05 10:28:40

标签: c arrays pointers

我理解为什么这不起作用:

int main(int argc, char *argv[]) {
    char *names[] = {"name1", "name2", "name3", "name4"};
    int i = 0;
    while (i++ <= 3) {
        printf("%s\n", *names++);
    }
}

错误:

a.c: In function 'main':
a.c:16: error: wrong type argument to increment
shell returned 1

这是因为我试图增加数组变量(而不是指针)。请不要介意错误消息中的行号,我在上面和下面列出了很多注释代码。

但是,我不明白为什么这段代码有效:

void myfunc(char *names[]) {
    int i = 0;
    while (i++ <= 3) {
        printf("%s\n", *names++);
    }
}


int main(int argc, char *argv[]) {
    char *names[] = {"name1", "name2", "name3", "name4"};
    myfunc(names);
}

我们如何在names中增加myfunc()?它仍然是myfunc()中的局部数组变量。 有人可以帮忙吗?

感谢。

3 个答案:

答案 0 :(得分:5)

在1 st 示例中,names是一个数组。数组无法递增。

在2 nd 示例中,names是一个指针。指针可以递增。

2 nd 示例编译原因的背景:

函数声明中变量定义中的[]与(另一个)*相同。

所以这个

void myfunc(char * names[]);

相当于

void myfunc(char ** names);

后者很明显,这里names不是数组而是指针。

答案 1 :(得分:1)

当您将数组作为函数参数传递时,它会将其转换为指向数组中第一个元素的指针。这意味着当您声明一个数组并尝试直接递增它时,您试图增加一个数组。另一方面,当您将数组作为参数传递时,它将作为指针传递,因此您可以将其递增。

如果您希望将数组作为数组传递,而不是作为指针传递,则可以考虑使用If any of the scores is within the top ten for this specific score keep the entry. If none of the scores is within the top ten for this specific score discard it. ,这是一个固定大小的容器。

编辑:我道歉。 std::array仅适用于C ++。

答案 2 :(得分:1)

当您将数组传递给函数时,它会衰减为指针。 请参阅此处了解array-decaying

相关问题