为什么这个阵列不够大?

Tre*_*e14 1 c memory

我已经运行了这个随机游走模拟一段时间了,我不断收到EXC_BAD_ACCESS来自Xcode 的错误.虽然它打印出大部分模拟.

我认为它由于某种原因而耗尽内存,但我不确定原因.

如果我走向数组的末尾,我编辑它,所以我不会在边缘的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);
}
Run Code Online (Sandbox Code Playgroud)

tan*_*grs 7

数组索引从零开始.

你的意思是写这个吗?

    places[i][0] = xPos; //Zeroth element is considered the first element
    places[i][1] = yPos; //Second element
Run Code Online (Sandbox Code Playgroud)

  • 没问题.它发生在我们最好的人:) (2认同)