2012-01-08 86 views
1

我一直在運行這個隨機遊走模擬一段時間,我一直從Xcode得到一個錯誤EXC_BAD_ACCESS。儘管如此,它還是打印出大部分的模擬結果。爲什麼這個數組不夠大?

我認爲它由於某種原因耗盡內存,但我不知道爲什麼。

如果我走向陣列末尾,我編輯它,所以我沒有得到邊緣的100個空格(通過編輯步驟-100的變量步驟)。這工作,但我想知道發生了什麼事。

任何幫助,將不勝感激。

double** places; 
places = (double**) malloc(steps*sizeof(double*)); 
for (int i = 0; i < steps; i++)places[i] = (double*) malloc(2*sizeof(double)); 

for (i = 0; i< steps/*, exit*/; i++) { 
    // Find the angle of movement 
    angle = getRand()*360; 
    // Take a step 
    xPos+= STEP*cos(angle); 
    yPos+= STEP*sin(angle); 
    //Write Step to array 
    places[i][1] = xPos; 
    places[i][2] = yPos; 
    //Write Step to File 
    fprintf(ff, "%d %lf %lf\n",i,xPos,yPos); 
} 

回答

7

數組索引從零開始。

您是不是要寫這個?

places[i][0] = xPos; //Zeroth element is considered the first element 
    places[i][1] = yPos; //Second element 
+0

哦,謝天謝地!現在我覺得自己像個白癡。我知道這一點,但我完全混淆了它。 – Treesrule14 2012-01-08 06:04:43

+2

沒問題。它發生在我們最好的:) – tangrs 2012-01-08 06:06:10

0

您已經分配了正確大小的數組(步驟x 2),但是您正在寫入子數組上的錯誤偏移量。它們應該是[0]和[1],而不是[1]和[2]。

[2]實際上是第3個數組元素,所以你寫在子數組的邊界之外。

0

內陣列(位於places[i])具有用於兩個元件空間 - 由[0][1]索引,因爲數組的下標通常C.從零開始在這裏,你索引它們與[1][2]。您需要使用[0][1],或者爲三個元素分配足夠的空間(並浪費分配給[0]的空間)。

0

索引從0

開始這應該是:

places[i][0] = xPos; 
places[i][1] = yPos; 
0

你關閉的一個。 C中的數組是基於零的,因此第一個元素位於位置0.您需要將您的賦值更改爲位置數組,如下所示:

// Write Step to array 
places[i][0] = xPos; 
places[i][1] = yPos; 
相關問題