澄清为什么这个C代码工作

ath*_*aos 7 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;
}
Run Code Online (Sandbox Code Playgroud)

所以我用Google搜索,最后改变了这条线

setText(&output);
Run Code Online (Sandbox Code Playgroud)

setText(output);
Run Code Online (Sandbox Code Playgroud)

摆脱了警告.但现在我不知道为什么第一个人正在工作.就我所知,我正在发送一个地址的地址(因为char*x;与char x [];本质上是相同的).我误解了什么,为什么这两个都有效?

Oli*_*rth 17

is 的类型,在函数调用的上下文中衰减为a (这就是第二个变体工作的原因).outputchar [10]char *

&outputis 的类型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);
}
Run Code Online (Sandbox Code Playgroud)

推荐阅读是关于数组和指针的C FAQ,特别是问题6.3和6.12.