【发布时间】:2021-05-13 01:06:07
【问题描述】:
对于我的项目,我需要将 PPM(P3) 图像读入内存。因为我想旋转输入图片,因此我想通过一个 x 和 y 轴/数组。
首先,我将图像的值读入“无符号字符”,因为使用的颜色值仅在 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 像素左右的图片大小时失败了。
【问题讨论】:
-
color (*inputColor)[pictureWidth] = malloc(pictureHeight * sizeof *inputColor);。与inputColor[y][x].red...一起使用它。 -
我已经尝试过了,但是我得到了“分段错误(核心转储)”。
-
假设您有一个符合 C99 的编译器:Correctly allocating multi-dimensional arrays
-
@mch: 回答一下。
标签: arrays c pointers struct malloc