1. 程式人生 > >C語言中指標中的值賦值給陣列

C語言中指標中的值賦值給陣列

  如果把各種語言做個冷兵器類比的話,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語言基本功的訓練,看來不能鬆懈啊.