歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C語言:指針參數的傳遞

C語言:指針參數的傳遞

日期:2017/3/1 10:30:37   编辑:Linux編程

指針是C語言的精華,也是C語言的難點!

今天寫程序,就犯了個很SB的指針錯誤。害我忙乎了大半天。我在這裡把問題抽象出來,給大家做個借鑒!避免以後也犯同樣的錯誤!

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

運行結果:

[cpp]

  1. [[email protected] test]# gcc parameter_deliver.c -o parameter_deliver
  2. [[email protected] 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. [[email protected] test]#

最開始我使用的是func2()的方法,一直得不到返回值,str數組的值一直不變。害我忙乎了半天,終於找到了原因。原來是我在被調函數fun2()裡面又重新malloc了,將以前的str傳遞給ptr的地址值給覆蓋了,所以我在func2()裡面對ptr的所有操作,都是局部操作,所有數據將在func2()退出的時候自動銷毀!⊙﹏⊙b汗~~~!!!

Copyright © Linux教程網 All Rights Reserved