2012-01-08 92 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; 
相关问题