我一直在尝试为 bmp 文件动态分配内存。我之前使用的是常量值,它工作得很好,但是当我尝试实现另一篇文章中的代码时: C Programming: malloc() inside another function我正在尝试为 bmp 的每个内存位置分配 RGB 值。
我收到段错误(核心转储)错误。
谁能告诉我我做错了什么?
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/为 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()
需要一个指向第一个值的指针。但像素是一个二维数组,即指向值的指针数组。相反,请尝试:
fread( &pixels[0][0], sizeof(unsigned char) , picHeight * picWidth * 3 , inputfile1);
其中 &pixels[0][0]
是指向 2D 数组第一个值的指针。
必须对 fwrite()
进行相同的修改。
关于c - 如何在 C 中为 2D 数组 bmp 文件动态分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35296420/