如何在C中为2D数组bmp文件动态分配内存?

时间:2016-02-09 15:55:51

标签: c arrays malloc

我一直在尝试为bmp文件动态分配内存。我之前使用的是常量值并且它工作正常但是当我尝试从另一个帖子实现代码时: C Programming: malloc() inside another function我试图为具有RGB值的bmp的每个内存位置分配。

我收到了分段错误(核心转储)错误。

谁能告诉我我做错了什么?

int main(){
unsigned char **pixels;
scanf("%d %d", &picHeight, &picWidth);
// dynamically allocate memory for height and width.
pixels = malloc(picHeight * sizeof *pixels);
int i;
    for ( i = 0; i < picHeight * 3; i+=3) {
        pixels[i] = malloc(picWidth * sizeof *pixels[i]);
        pixels[i+1] = malloc(picWidth * sizeof *pixels[i]);
        pixels[i+2] = malloc(picWidth * sizeof *pixels[i]);
    }

fread( header, 1 , HEADER_SIZE , inputfile1);
fread( pixels, 1 , picHeight * picWidth * 3 , inputfile1);

darken(pixels, picHeight, picWidth);
fclose(inputfile1);

fclose(outputfile1);
return 0;
}

void darken(unsigned char** pixels, int picHeight, int picWidth) {
int r,c;

for( r = 0; r < picHeight; r++) {
     for ( c = 0; c < picWidth * 3; c += 3) {
         int temp1 = pixels[r][c];
         int temp2 = pixels[r][c+1];
         int temp3 = pixels[r][c+2];

         temp1 = temp1 - 50;
         temp2 = temp2 - 50;
         temp3 = temp3 - 50;
         if(temp1 < 0) temp1 = 0;
         if(temp2 < 0) temp2 = 0;
         if(temp3 < 0) temp3 = 0;

         pixels[r][c] = temp1;
         pixels[r][c+1] = temp2;
         pixels[r][c+2] = temp3;
     }
}
fwrite( header, sizeof(char)  , HEADER_SIZE  ,  outputfile1);
fwrite( pixels, sizeof(char)  , picHeight * picWidth * 3  ,  outputfile1);
}

完整的代码非常冗长,所以我不想全部包含它。

1 个答案:

答案 0 :(得分:0)

1 / 2D阵列的已分配内存大小太小:这可能会触发分段错误。尝试:

pixels = malloc(picHeight * sizeof(*pixels)*3);

2 /如果您只想调用fread一次,则连续行的值必须在内存中连续。请参阅Allocate memory 2d array in function C并尝试:

pixels = malloc(picHeight * sizeof(*pixels)*3);
pixels[0]=malloc(picHeight * sizeof(unsigned char)*3*picWidth);
int i;
for(i=0;i<picHeight*3;i++){
    pixels[i]=&pixels[0][i*picWidth];
}

不要忘记free()最后的记忆!

3 / fread()需要指向第一个值的指针。但是pixels是一个2D数组,它是一个指向值的指针数组。相反,尝试:

fread( &pixels[0][0], sizeof(unsigned char) , picHeight * picWidth * 3 , inputfile1);

其中&pixels[0][0]是指向2D数组的第一个值的指针。 必须对fwrite()进行相同的修改。

相关问题