0
這個小C程序每次都會崩潰。爲什麼這個程序崩潰?
它應該以3D格式的形式分配一塊內存,該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;
}
[不要施放malloc(和朋友)的結果](http://stackoverflow.com/q/605845) – Deduplicator 2014-09-19 19:18:13
用所有的警告和調試信息('gcc -Wall -g')編譯你的程序。然後**使用調試器**('gdb') – 2014-09-19 19:19:56
您在計算索引時混淆了尺寸。 – Deduplicator 2014-09-19 19:20:10