我发现自己无法解释为什么以下代码有效。不用说,我对 C++ 很陌生......
#include <cstdio>
void foo(char* p)
{
p[0] = 'y';
}
int main()
{
char a[1];
a[0] = 'x';
printf("a[0] = %c\n", a[0]);
foo(a);
printf("a[0] = %c\n", a[0]);
return 0;
}
这个程序输出
a[0] = x
a[0] = y
令我感兴趣的是,我没有向 foo 传递一个指针,而是一个数组。那么foo如何改变数组a的值呢?这是否仅适用于 char 数组?
Difference between char and char[1] 的答案,证实了我的观察,但没有详细说明为什么会出现这种情况。
谢谢!
最佳答案
当您将数组传递给函数时,它会衰减为指向第一个元素的指针。
以下是完全等价的:
void foo(char* p);
void foo(char p[]);
void foo(char p[42]); /* Or any other number. */
Does this apply only to arrays of char?
它适用于任何数组。我推荐aryptr section of the C FAQ .
关于c++ - 函数调用中char[]和char*的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9359269/