【问题标题】:how do I dynamically allocate memory for a 2D array bmp file in C.?如何在 C. 中为二维数组 bmp 文件动态分配内存?
【发布时间】:2016-02-09 15:55:51
【问题描述】:

我一直在尝试为 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);
}

完整的代码真的很长,所以我不想全部包含在内。

【问题讨论】:

  • 提供minimal reproducible example。您的代码中没有二维数组。
  • 在循环中一次分配三个而不是一次分配一个是否有原因?无论如何,i &lt; picHeight * 3 是行不通的。你只分配了picHeight 指针,pixels[picHeight ... 3 * picHeight - 1] 访问未分配的内存。最后但同样重要的是,指针不是数组也不是指针:你有一个指向指针的指针,而不是二维数组。
  • 您的调试器会告诉您在哪里发生崩溃。
  • 我在 gedit 中运行 ubuntu 我没有用于此类的调试器。

标签: c arrays malloc


【解决方案1】:

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 是一个二维数组,即指向值的指针数组。相反,请尝试:

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

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

【讨论】:

  • 谢谢!很好的答案!我知道我离得不远,只是当它第一次不起作用并且你开始改变东西并将整个事情搞砸时令人沮丧。
猜你喜欢
  • 2014-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-11
相关资源
最近更新 更多