gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:21:43 26 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/13431108/

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