如果把各種語言做個冷兵器類比的話,C語言一定是刀客的最佳工具.入門很簡單,但是要是能把它熟練運用,那就是頂尖級別的高手了.
用了那么多年的C語言,發現自己還是僅僅處於熟練的操作工.今天遇到了一個bug,就是和指針的賦值有關系.請看代碼:
1 #include <stdio.h> 2 3 static int array[2]; 4 int main() 5 { 6 7 int *ptest = NULL; 8 9 ptest = (int*)malloc(2*sizeof(int)); 10 11 ptest[0] = 32767; 12 ptest[1] = -32767; 13 14 array = ptest; 15 printf("val1:%d val2:%d \n",array[0],array[1]); 16 17 return 0; 18 19 } 20 ~
各位看官,能否看到這個代碼的問題嗎?
其實,這段代碼有個嚴重的問題,就是把指針的地址指向了數組的地址,就是把一個值打算放到兩個地址中,這個是肯定不對的了.讓在復雜的代碼叢林中,沒有意識到這個用法時候,那就很容易把指針混為一體.
假如array是個指針的話,那這份代碼九對了.
正確的寫法如下所示:
1 #include <stdio.h> 2 3 //static int array[2]; 4 int *array= NULL; 5 int main() 6 { 7 8 int *ptest = NULL; 9 10 ptest = (int*)malloc(2*sizeof(int)); 11 12 ptest[0] = 32767; 13 ptest[1] = -32767; 14 15 array = ptest; 16 printf("val1:%d val2:%d \n",array[0],array[1]); 17 18 return 0; 19 20 }
對C語言基本功的訓練,看來不能松懈啊.