void s(int* a, int* b) {
a=b;
}
int main(int argc, char* argv[]) {
int* a = malloc(sizeof(int));
int* b = malloc(sizeof(int));
int c = 10;
int d = 5
a = &c;
b = &d;
printf("%d %d\n",*a,*b);
s(a,b);
printf("%d %d\n",*a,*b);
}
我真的很困惑。这是非常简单的代码。我认为这会导致 a 和 b 指向相同的值。当我在主函数内部执行 a=b 时,一切都会按预期工作。当我使用 gdb 时,它甚至显示它们指向内存中的同一位置,并且该函数没有被优化掉!那么到底发生了什么? 该函数是否正在创建自己的本地副本?为什么这些不指向同一个变量,请帮忙。
最佳答案
您想要更改指针值。指针是按值传递的,因此您需要一个指向指针的指针来更改其值:
#include <stdio.h>
void s(int** foo, int** bar)
{
*foo = *bar;
}
int main(void)
{
int c = 10;
int d = 5;
int *a = &c;
int *b = &d;
printf("%d %d\n", *a, *b); // 10 5
s(&a, &b);
printf("%d %d\n", *a, *b); // 5 5 a points at d as well
}
在您的版本中,您仅更改了参数,这些参数是传递给函数的值的副本。
为了帮助您更好地理解,请考虑以下内容:
#include <stdio.h>
void value(int foo, int bar)
{
foo = bar; // changing local copies
}
void pointer(int *foo, int *bar)
{
*foo = *bar; // changing the value foo points to to the value bar points to
}
int main(void)
{
int a = 5;
int b = 7;
value(a, b);
printf("%d, %d\n", a, b); // 5, 7
pointer(&a, &b);
printf("%d, %d\n", a, b); // 7, 7
}
我们用int
类型做到了这一点。现在让我们用 int*
替换 int
:
#include <stdio.h>
void value(int *foo, int *bar)
{
foo = bar; // changing local copies
}
void pointer(int **foo, int **bar)
{
*foo = *bar; // changing the value foo points to to the value bar points to
}
int main(void)
{
int x = 5;
int y = 7;
int *a = &x;
int *b = &y;
value(a, b);
printf("%d, %d\n", *a, *b); // 5, 7
pointer(&a, &b);
printf("%d, %d\n", *a, *b); // 7, 7 now both point at y
}
所以你看,这两次都是同一个概念。在第一个示例中,指向的值是 int
,它们的值是数字,在第二个示例中,指向的值是 int*
,它们的值是指针值( <~ 标准术语,“地址”)。但机制是一样的
关于C 指针未设置为等于另一个指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56051362/