C语言:指针参数的传递


指针是C语言的精华,也是C语言的难点!

今天写程序,就犯了个很SB的指针错误。害我忙乎了大半天。我在这里把问题抽象出来,给大家做个借鉴!避免以后也犯同样的错误!

  1. #include <stdio.h>   
  2. #include <stdlib.h>   
  3. #include <string.h>   
  4.   
  5. void func1(char *ptr)  
  6. {  
  7.     ptr[0] = 55;  
  8.     printf("address of ptr is %p\n", (unsigned)ptr);  
  9.     printf("value of ptr[0] is %d\n", ptr[0]);  
  10. }  
  11.   
  12. void func2(char *ptr)  
  13. {  
  14.     ptr = (char *)malloc(10);  
  15.     ptr[0] = 66;  
  16.     printf("address of ptr is %p\n", (unsigned)ptr);  
  17.     printf("value of ptr[0] is %d\n", ptr[0]);  
  18. }  
  19.   
  20. void main()  
  21. {  
  22.     char *str;  
  23.     str = (char *)malloc(10);  
  24.     printf("*******************************\n");  
  25.     memset(str,'\0',sizeof(str));  
  26.     printf("address of str is %p\n", (unsigned)str);  
  27.     printf("value of str[0] is %d\n", str[0]);  
  28.     printf("*******************************\n");  
  29.     memset(str,'\0',sizeof(str));  
  30.     func1(str);  
  31.     printf("address of str is %p\n", (unsigned)str);  
  32.     printf("value of str[0] is %d\n", str[0]);  
  33.     printf("*******************************\n");  
  34.     memset(str,'\0',sizeof(str));  
  35.     func2(str);  
  36.     printf("address of str is %p\n", (unsigned)str);  
  37.     printf("value of str[0] is %d\n", str[0]);  
  38.     printf("*******************************\n");  
  39. }  

运行结果:

[cpp]

  1. [root@www.bkjia.com test]# gcc parameter_deliver.c -o parameter_deliver  
  2. [root@www.bkjia.com test]# ./parameter_deliver   
  3. *******************************  
  4. address of str is 0x995b008  
  5. value of str[0] is 0  
  6. *******************************  
  7. address of ptr is 0x995b008  
  8. value of ptr[0] is 55  
  9. address of str is 0x995b008  
  10. value of str[0] is 55  
  11. *******************************  
  12. address of ptr is 0x995b018  
  13. value of ptr[0] is 66  
  14. address of str is 0x995b008  
  15. value of str[0] is 0  
  16. *******************************  
  17. [root@www.bkjia.com test]#   

最开始我使用的是func2()的方法,一直得不到返回值,str数组的值一直不变。害我忙乎了半天,终于找到了原因。原来是我在被调函数fun2()里面又重新malloc了,将以前的str传递给ptr的地址值给覆盖了,所以我在func2()里面对ptr的所有操作,都是局部操作,所有数据将在func2()退出的时候自动销毁!⊙﹏⊙b汗~~~!!!

  • 1
  • 2
  • 下一页

相关内容