gpt4 book ai didi

使用函数更改指针包含的地址

转载 作者:行者123 更新时间:2023-11-30 16:19:06 25 4
gpt4 key购买 nike

如果我将指针p声明为int *p;在主模块中,我可以通过分配 p = &a; 来更改 p 包含的地址,其中 a 是另一个已声明的整数变量。我现在想通过使用以下函数来更改地址:

void change_adrs(int*q)
{
int *newad;
q = newad;
}

如果我从主模块调用这个函数

int main()
{
int *p;
int a = 0;
p = &a; // this changes the address contained by pointer p
printf("The address is %u\n", p);
change_adrs(p);
printf("The address is %u\n", p); // but this doesn't change the address
return 0;
}

地址内容不变。使用函数执行同一任务有什么问题?

最佳答案

在 C 语言中,函数参数是按值传递的。因此,您的参数会生成一个副本,并且对该副本进行更改,而不是您期望看到修改的实际指针对象。如果您想这样做,您将需要更改函数以接受指针到指针参数,并对取消引用的参数进行更改。例如

 void foo(int** p) {
*p = NULL; /* set pointer to null */
}
void foo2(int* p) {
p = NULL; /* makes copy of p and copy is set to null*/
}

int main() {
int* k;
foo2(k); /* k unchanged */
foo(&k); /* NOW k == NULL */
}

如果您有能力使用 C++,另一种方法是更改​​函数以接受对指针的引用。

关于使用函数更改指针包含的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55700670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com