2011-04-28 51 views
0

我有一個20x20矩陣。我想從矩陣中提取大塊數據。我有如何通過指針迭代2維數組?

int theMatrix[20][20] = {};//Full code initializes with #'s 
int *theMatrixPointer = &theMatrix; 

但後來我得到一個編譯器警告說

警告:初始化從 兼容的指針類型

我繼續跑的代碼,它看起來是運動從矩陣的左邊到右邊。至少在短期內。執行:

//left to right with pointer; 
while(theMatrixPointer) 
{ 
    int one = 0; 
    int two = 0; 
    int three = 0; 
    int four = 0; 
    double currentProduct = 0; 
    //int stop = 0; 
    for(int i = 0; i < depth; i++) 
    { 
     /*if(!theMatrixPointer) 
     { 
      stop = 1; 
      break; 
     }*/ 
     int currentValue = *theMatrixPointer++; 
     printf("%d\n",currentValue); 
     if(i == 0) 
     { 
      one = currentValue; 
     } 
     else if (i == 1) 
     { 
      two = currentValue; 
     } 
     else if (i == 2) 
     { 
      three = currentValue; 
     } 
     else if (i == 3) 
     { 
      four = currentValue; 
     } 
    } 
    /*if(stop) 
     break;*/ 
    currentProduct = one * (double)two * three * four; 
    printf("PRODUCT: %f\n",currentProduct); 
    startPoint++; 
    theMatrixPointer = startPoint; 
} 

...由於數據是垃圾(大整數不在矩陣中)而隨時間而中斷。那麼,我該如何正確地用指針迭代這個矩陣呢?

回答

1

首先,您收到警告的原因是因爲&theMatrix的類型爲int(*)[20][20],而theMatrixPointer的類型爲int *。你需要這個:

int *theMatrixPointer = &theMatrix[0][0]; 

其次,你得到垃圾的原因是因爲你要經過數組的末尾。 while (theMatrixPointer)將迭代到theMatrixPointer == 0。但請記住theMatrixPointer的地址。這不會是0,直到您遍歷整個整個地址空間並且迴繞!

你可能是最好關閉這樣做:

int i, j; 
for (i = 0; i < 20; i++) 
{ 
    for (j = 0; j < 20; j++) 
    { 
     // matrixPointer[i][j] is the current element 
    } 
} 
+0

與i,j指數迭代路線的問題是,我計劃出的算法不起作用。我需要一次從矩陣4中拉出塊。在每次拉動之後,下一個索引需要通過沖洗重複進行。在一個類似的,但不同的問題上,我用一個字符串和指針乾淨地解決了這個問題,但是這個矩陣證明了更具挑戰性。我可能需要重新考慮我的方法。 – 2011-04-28 21:03:55

+0

@ssegvic謝謝你們,我現在知道如何用指針來做到這一點。 – 2011-04-29 12:44:45

1

檢查我的回答類似的問題here。基本上,我認爲處理矩陣[20 * 20]是比處理矩陣[20] [20]更明智的默認方法。