C语言:指针参数的传递
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");
- }
运行结果:
[cpp]
- [root@www.bkjia.com test]# gcc parameter_deliver.c -o parameter_deliver
- [root@www.bkjia.com 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
- *******************************
- [root@www.bkjia.com test]#
最开始我使用的是func2()的方法,一直得不到返回值,str数组的值一直不变。害我忙乎了半天,终于找到了原因。原来是我在被调函数fun2()里面又重新malloc了,将以前的str传递给ptr的地址值给覆盖了,所以我在func2()里面对ptr的所有操作,都是局部操作,所有数据将在func2()退出的时候自动销毁!⊙﹏⊙b汗~~~!!!
|
评论暂时关闭