我今天在学习 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[]; 相同)。我误解了什么,为什么这两种方法都有效?
最佳答案
output
的 type 是 char [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/