为什么这个程序崩溃了?

时间:2014-09-19 19:15:47

标签: c crash

这个小C程序每次都会崩溃。

应该以3D友好模式中以布置在存储器中的许多结构(单元)组成的3D网格的形式分配一块存储器。结构将填充位置数据。

我不知道为什么会崩溃。它返回这个数字:c0000005。

#include <stdio.h>
#include <malloc.h>

typedef struct {
int coords[3];
} cell;

int main() {

    int x=4, y=8, z=6;

    int volume=x*y*z;

    cell *arr=(cell*)calloc(volume,sizeof(cell));

    int u=0,v=0,w=0;
    int index;

    for (w=0; w<z; w++) {
    for (v=0; v<y; v++) {
    for (u=0; u<x; u++) {

        //printf("%d %d %d\n", u, v, w);

        index=u+v*y+w*y*z;

        arr[index].coords[0]=u;
        arr[index].coords[1]=v;
        arr[index].coords[2]=w;

        //getchar();

    }}}

    printf("All done.\n");

    return 0;
}

1 个答案:

答案 0 :(得分:2)

问题是index=u+v*y+w*y*z;

应为index=u+v*x+w*y*x;

所以@nos是对的。它会触发分段错误,因为6=z>x=4index会变得过大。

相关问题