[英]Allocating a 2-dimensional structure array with malloc
對於我的項目,我需要將 PPM(P3) 圖像讀入 memory。 因為我想旋轉輸入圖片,因此我想通過 x 和 y 軸/陣列來 go。
首先,我將圖像的值讀入“無符號字符”,因為使用的顏色值僅在 0 到 255 之間,為了保存 memory,我將它們轉換為無符號字符。
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 像素的圖片大小附近失敗了。
雙指針解決方案在考慮圖像時有一個非常薄弱的地方。 它們不能直接傳送到屏幕 memory 或訪問快速方式。
更好的是使用指向數組的指針。
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));
}
mch 發布的指向數組方法的指針,我相信這將是最好的方法:
#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);
}
第一個malloc
為pictureHeight
的行數分配memory, for
循環為每一行分配memory,大小為pictureWidth
。
訪問與指向數組方法的指針相同。
在這些簡化的代碼中,沒有執行錯誤檢查,這是您應該做的事情,即檢查 malloc 返回值是否存在錯誤。
完成后不要忘記釋放 memory:
對於第一個示例:
free(inputColor);
對於第二個:
for (int y = 0; y < pictureHeight; y++)
{
free(inputColor[y]);
}
free(inputColor);
只需分配一個雙指針並為其分配 memory :
color **inputColor;
inputcolor= malloc(sizeof(color*)*pictureHeight);
for (int y = 0; y < pictureHeight; y++){
inputColor[y] = malloc(sizeof(color)*pictureWidth);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.