[英]Bus error 10 with 2d array of struct inside struct
我在结构中填充结构的二维数组时遇到问题。 它允许我为像素[0] [1],像素[0] [2] ....等做。 但是,一旦我增加第一个索引,即像素[1] [1],我得到一个总线错误10.任何帮助将不胜感激。 我已经删除了一些代码以使其更具可读性,但如果您需要所有代码,请告诉我! 程序正在做的是读取PPM图像并显示信息,我遇到的麻烦是存储图像的像素。
#define MAX_HEIGHT 4
#define MAX_WIDTH 4
typedef struct Pixel{
int red;
int green;
int blue;
}Pixel;
typedef struct PPM{
char code[2];
int width, height;
int max;
Pixel * pixels[MAX_HEIGHT][MAX_WIDTH];
}PPM;
struct PPM * getPPM(FILE * fd){
PPM * image = NULL;
image = malloc(sizeof(PPM));
//have got all the other PPM info here ask if needed
int i;
int j;
for(i = 0; i<MAX_HEIGHT-1; i++){
for(j = 0; j<MAX_WIDTH-1; j++){
// struct Pixel newPPM_Pixel;
if(fscanf(fd, "%d %d %d", &image->pixels[i][j]->red, &image->pixels[i][j]->green, &image->pixels[i][j]->blue) == 3){
//rgb_array[i][j] = newPPM_Pixel;
printf("/ %d / %d / %d", image->pixels[i][j]->red, image->pixels[i][j]->green, image->pixels[i][j]->blue);
}
}
}
return image;
}
换线:
Pixel * pixels[MAX_HEIGHT][MAX_WIDTH];
至 :
Pixel pixels[MAX_HEIGHT][MAX_WIDTH]; //without an asterisk
这是声明2D数组的方法。 如果您希望pixels
成为指针,请将其声明为:
Pixel **pixels;
然后为它动态分配内存:
int i;
pixels = malloc (MAX_HEIGHT*sizeof(Pixel*));
if (pixels == NULL)
printf ("Error allocating memory\n");
for (i = 0; i < MAX_HEIGHT; i++)
pixels[i] = malloc(MAX_WIDTH*sizeof(Pixel));
if (pixels[i] == NULL)
printf ("Error allocating memory\n");
您可以在此处阅读有关2D动态内存分配的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.