说明此 C 代码为何有效

标签 c pointers

我今天在学习 C。我使用托管语言(Java、C#、Python 等)编码已有一段时间了。我以为我理解了指针的细节,但后来我编写了以下代码,它按预期工作,但生成了“不兼容的指针类型”警告。

void setText(char* output) {
    //code to set output to whatever, no problems here.
}

int main(int argc, const char* argv[]) {
    char output[10];

    setText(&output);

    //[EDITED] ...other test code which printf's and further manipulates output.

    return 0;
}

所以我用谷歌搜索,最后改了行

setText(&output);

setText(output);

去掉了警告。但现在我不知道为什么第一个在所有工作。据我所知,我正在发送一个地址的地址(因为 char* x; 本质上与 char x[]; 相同)。我误解了什么,为什么这两种方法都有效?

最佳答案

outputtypechar [10],在上下文中衰减为 char *函数调用(这就是第二个变体起作用的原因)。

&output的类型是char (*)[10],即指向数组的指针。这不是一回事,因此会出现编译器警告。但是,&output(地址)的等同于output的值(一旦它衰减为char * ),所以最终结果是“如预期的那样”。

这听起来有点迂腐,但有一个相当重要的区别。尝试以下操作:

void foo(const char *p)
{
    printf("%s\n", p);
}

int main(void)
{
    char output[][6] = { "Hello", "world" };

    foo(output[0] + 1);
    foo(&output[0] + 1);
}

推荐阅读the C FAQ on arrays and pointers ,特别是问题 6.3 和 6.12。

关于说明此 C 代码为何有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6565350/

相关文章:

c - 如何使用指向数组的指针打印从二维数组传递的字符串?

c - 如何在 C 中创建一个新的列表头?

c - MPI协议(protocol)中的MPI_Comm如何实现?

c - 如何优化这段代码?

c - inotify_event 返回 wd -1

c - 将指向结构的指针分配给变量

c++ - 指针声明和间接声明之间的区别

由 c++ Mysql C API mysql_real_escape_string

c - 冗余 __packed__ 属性

c++ - 在 C++ 中处理指针数组并删除它们