指針是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]
- [[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汗~~~!!!