使用函数更改指针包含的地址如果我声明了一个指针p如int *p;在主模块中,我可以更改p通过分配p=&a;哪里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("\n The address is %u ",p);
change_adrs(p);
printf("\n the address is %u ",p); // but this doesn't change the address
return 0;}地址内容不变。在相同的任务中使用函数有什么问题?
3 回答
噜噜哒
TA贡献1784条经验 获得超7个赞
void foo(int** p) { *p = 0; /* set pointer to null */ } void foo2(int* p) { p = 0; /* makes copy of p and copy is set to null*/ } int main() { int* k; foo2(k); /* k unchanged */ foo(&k); /* NOW k == 0 */ }
繁星coding
TA贡献1797条经验 获得超4个赞
void change(int **p, int *someOtherAddress){ *p = someOtherAddress;}int a = 1, b = 2;int *p = &a;printf("*p = %d\n", *p);change(&p, &b);printf("*p = %d\n", *p);
*p = 1 *p = 2
九州编程
TA贡献1785条经验 获得超4个赞
&
*
*
#include <stdio.h>#include <stdlib.h>void changeIntVal(int *x) { *x = 5;}void changePointerAddr(int **q) { int *newad; *q = newad;}void changePPAddr(int ***q) { int **dummy; *q = dummy;}int main() { int *p; int **pp; int *tempForPP; int a = 0; printf("\n The address pointing by p -> %p, pp -> %p, value of a -> %d ", p, pp, a); p = &a; pp = &tempForPP; printf("\n The address pointing by p -> %p, pp -> %p, value of a -> %d ", p, pp, a); changeIntVal(&a); // ---- // |--- changePointerAddr(&p); // ---- |----> parts of what I mean // |--- changePPAddr(&pp); // ---- printf("\n The address pointing by p -> %p, pp -> %p, value of a -> %d ", p, pp, a); return 0;}
- 3 回答
- 0 关注
- 590 浏览
添加回答
举报
0/150
提交
取消