C语言:指针参数的传递
指针是C语言的精华,也是C语言的难点!
今天写程序,就犯了个很SB的指针错误。害我忙乎了大半天。我在这里把问题抽象出来,给大家做个借鉴!避免以后也犯同样的错误!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- void func1(char *ptr)
- {
- ptr[0] = 55;
- printf("address of ptr is %p\n", (unsigned)ptr);
- printf("value of ptr[0] is %d\n", ptr[0]);
- }
- void func2(char *ptr)
- {
- ptr = (char *)malloc(10);
- ptr[0] = 66;
- printf("address of ptr is %p\n", (unsigned)ptr);
- printf("value of ptr[0] is %d\n", ptr[0]);
- }
- void main()
- {
- char *str;
- str = (char *)malloc(10);
- printf("*******************************\n");
- memset(str,'\0',sizeof(str));
- printf("address of str is %p\n", (unsigned)str);
- printf("value of str[0] is %d\n", str[0]);
- printf("*******************************\n");
- memset(str,'\0',sizeof(str));
- func1(str);
- printf("address of str is %p\n", (unsigned)str);
- printf("value of str[0] is %d\n", str[0]);
- printf("*******************************\n");
- memset(str,'\0',sizeof(str));
- func2(str);
- printf("address of str is %p\n", (unsigned)str);
- printf("value of str[0] is %d\n", str[0]);
- printf("*******************************\n");
- }
运行结果:
- [[email protected] test]# gcc parameter_deliver.c -o parameter_deliver
- [[email protected] test]# ./parameter_deliver
- *******************************
- address of str is 0x995b008
- value of str[0] is 0
- *******************************
- address of ptr is 0x995b008
- value of ptr[0] is 55
- address of str is 0x995b008
- value of str[0] is 55
- *******************************
- address of ptr is 0x995b018
- value of ptr[0] is 66
- address of str is 0x995b008
- value of str[0] is 0
- *******************************
- [[email protected] test]#
最开始我使用的是func2()的方法,一直得不到返回值,str数组的值一直不变。害我忙乎了半天,终于找到了原因。原来是我在被调函数fun2()里面又重新malloc了,将以前的str传递给ptr的地址值给覆盖了,所以我在func2()里面对ptr的所有操作,都是局部操作,所有数据将在func2()退出的时候自动销毁!⊙﹏⊙b汗~~~!!!
相关推荐
拉斯厄尔高福 2020-10-19
徐建岗网络管理 2020-06-26
penkgao 2020-06-25
fengjing81 2020-06-24
chensen 2020-11-14
拉斯厄尔高福 2020-11-04
杜倩 2020-10-29
嵌入式资讯精选 2020-10-15
zhaochen00 2020-10-13
penkgao 2020-10-13
yiyilanmei 2020-10-05
wanshiyingg 2020-09-29
Mars的自语 2020-09-27
shenwenjie 2020-09-24
一个逗逗 2020-09-22
flycony 2020-09-13
zhaochen00 2020-08-20
Biao 2020-08-20
qingsongzdq 2020-08-19