这段代码给我一个seg错误
image_t* removeNoiseAverage(image_t* img[]) {
image_t* average = (image_t*) malloc(sizeof(image_t));
int image_size = img[0]->header.HEIGHT * img[0]->header.WIDTH;
int i,k;
double avg = 0;
for (i=0;i<image_size;i++){
avg = 0;
for (k=0;k<10;k++){
avg += img[k]->pixels[i].R;
}
avg = avg/10;
average->pixels[i].R = avg;
}
return 0;
}
typedef struct image {
header_t header; // 15 bytes
pixel_t* pixels; // 4 bytes
} image_t;
typedef struct pixel {
uint8_t R, G, B;
} pixel_t;
typedef struct header {
char MAGIC_NUMBER[3];
unsigned int HEIGHT, WIDTH, MAX_COLOR;
} header_t;
image_t
是我制作的结构,分段错误发生在average->pixels[i].R = avg;
我的malloc不正确吗?
编辑:已更新以添加声明
答案 0 :(得分:1)
image_t* average = (image_t*) malloc(sizeof(image_t));
这会为average
分配空间,但不为average->pixels
内部空间分配空间。两个指针意味着你需要两个分配。
average->pixels = malloc(image_size * sizeof(pixel_t));