使用 malloc 分配二维结构数组

Allocating a 2-dimensional structure array with malloc

对于我的项目,我需要将 PPM(P3) 图像读入内存。因为我想旋转输入图片,所以我想通过 x 和 y axis/array.

首先,我将图像的值读入“无符号字符”,因为使用的颜色值仅在 0 到 255 之间,为了节省内存,我将它们转换为无符号字符。

PPM 图像中的每个像素都有一个红色、绿色、蓝色值。

为此,我创建了这个 typedef struct

typedef struct{
    unsigned char red;
    unsigned char greed;
    unsigned char blue;
} color;

我试过像这样制作一个简单的二维数组:

color inputColor[pictureHeight][pictureWidth];

但是当图片变大时,这很快就会失败。 我试图让它工作,所以我可以用 malloc 分配那个二维数组。 一次尝试是:

color *inputColor[pictureHeight][pictureWidth];

//Allocating memory
for (int y = 0; y < pictureHeight; y++){
    for (int x = 0; x < pictureWidth; x++){
        inputColor[y][x] = malloc(sizeof(color));
    }
}

// Here i am copying values from an inputStream to the structure
int pixel = 0;
for (int y = 0; y < pictureHeight; y++){
    for (int x = 0; x < pictureWidth; x++){
        inputColor[y][x]->red = inputMalloc[pixel];
        pixel++;
        inputColor[y][x]->green = inputMalloc[pixel];
        pixel++;
        inputColor[y][x]->blue = inputMalloc[pixel];
        pixel++;
    }
}

但是在第一行又失败了...

如何用malloc分配一个二维结构数组,让图片大小不再那么重要?

现在它在 700x700 像素的图片大小附近失败。

,我认为最好的办法是:

#include <stdlib.h>

color (*inputColor)[pictureWidth] = malloc(pictureHeight * sizeof *inputColor);

访问与您使用的相同,inputColor[y] 用于行,inputColor[y][x] 用于列,inputColor[y][x].red 用于访问结构成员。

既然你说不行,那你可以试试指针对指针的方法,虽然慢一些,但可能更容易理解和应用:

color **inputColor;

inputColor = malloc(pictureHeight * sizeof *inputColor);

for (int y = 0; y < pictureHeight; y++)
{
    inputColor[y] = malloc(pictureWidth * sizeof **inputColor);
}

第一个 mallocpictureHeight 行分配内存,for 循环为每一行分配内存,大小为 pictureWidth.

访问与指向数组方法的指针相同。

在这些简化的代码片段中,没有执行任何错误检查,这是您应该做的事情,即检查 malloc return 值是否有错误。

不要忘记在用完后释放内存:

第一个例子:

free(inputColor);

第二个:

for (int y = 0; y < pictureHeight; y++)
{
    free(inputColor[y]);
}
free(inputColor);

只需分配一个双指针并为其分配内存:

color **inputColor;

inputcolor= malloc(sizeof(color*)*pictureHeight);
for (int y = 0; y < pictureHeight; y++){
        inputColor[y] = malloc(sizeof(color)*pictureWidth);
   
}

双指针解决方案在考虑图像时有一个非常弱的点。它们不能直接传输到屏幕内存或快速访问。

更好的方法是使用指向数组的指针。

typedef struct{
    unsigned char red;
    unsigned char greed;
    unsigned char blue;
} color;

int main(void)
{

    size_t pictureHeight = 600, pictureWidth = 800;

    color (*inputColor)[pictureHeight][pictureWidth];

    inputColor = malloc(sizeof(*inputColor));
}