您的位置:首页 > 其它

指针做形参

2016-11-16 15:28 190 查看

指针做形参

下面两个函数分别改变指针指向的内容和指针值,探索*p = i与p = &i的不同

void point(int *p)
{
printf("2. p = %d, addr p = %d, the p is %p\n", *p, &p, p);//其地址变了,说明是另一变量;指向的内存块数据和值没变
int i = 10;
*p = i;
printf("3. p = %d, addr p = %d, the p is %p\n", *p, &p, p);//地址和值没变;指向的内存块数据改变
i = 7;
printf("4. p = %d, addr p = %d, the p is %p\n", *p, &p, p);//地址和值指向的内存块数据都不变
}
void point1(int *p)
{
printf("7. p = %d, addr p = %d, the p is %p\n", *p, &p, p);//其地址变了,说明是另一变量;指向的内存块数据和值没变
int i = 10;
p = &i;
printf("8. p = %d, addr p = %d, the p is %p\n", *p, &p, p);//p的值改变为i的地址,即p指向i,此时p与r分别指向不同的内存块了,不会互相影响
i = 7;
printf("9. p = %d, addr p = %d, the p is %p\n", *p, &p, p);//p指向i,i指向的内存数据改变,p也跟着改变
}
int main()
{
int i = 6;
int a = 6;
int *q = &i;
int *r = &a;
printf("1. q = %d, addr q = %d, the q is %p\n", *q, &q, q);
point(q);
printf("5. q = %d, addr q = %d, the q is %p\n", *q, &q, q);
printf("6. r = %d, addr r = %d, the r is %p\n", *r, &r, r);
point1(r);
printf("10. r = %d, addr r = %d, the r is %p\n", *r, &r, r);
return 1;
}


print
1. q = 6, addr q = 3340996, the q is 0032FAD4
2. p = 6, addr p = 3341004, the p is 0032FAD4
3. p = 10, addr p = 3341004, the p is 0032FAD4
4. p = 10, addr p = 3341004, the p is 0032FAD4
5. q = 10, addr q = 3340996, the q is 0032FAD4
6. r = 6, addr r = 3341000, the r is 0032FAD0
7. p = 6, addr p = 3341004, the p is 0032FAD0
8. p = 10, addr p = 3341004, the p is 0032FAD8
9. p = 7, addr p = 3341004, the p is 0032FAD8
10. r = 6, addr r = 3341000, the r is 0032FAD0
请按任意键继续. . .


传入的指针仅仅是一个拷贝,方法不会改变原指针的地址、值,但是可能会改变原指针所指向内存块的数据。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  指针 函数