假设我们的位图图像具有高度 M 和宽度 N。在本实验中,我们将始终假设宽度 N 是 4 的倍数,这简化了文件中的字节布局。对于此图像,像素阵列以以下方式存储 3 x N x M 字节:
每组 3 个字节代表一个像素,其中字节按此顺序存储像素的蓝色、绿色和红色值。
像素按行分组。例如,像素阵列中的前 3 x N 个字节表示图像最顶行中的像素。
pixel_array_offset 是像素阵列开始的地方。
一个结构像素给出如下:
struct pixel {
unsigned char blue;
unsigned char green;
unsigned char red;
};
Run Code Online (Sandbox Code Playgroud)
这是实现该功能的要求:
/*
* Read in pixel array by following these instructions:
*
* 1. First, allocate space for m "struct pixel *" values, where m is the
* height of the image. Each pointer will eventually point to one row of
* pixel data.
* 2. For each pointer you just allocated, initialize it to point to
* heap-allocated space for an entire row of pixel data.
* 3. ...
* 4. ...
*/
struct pixel **read_pixel_array(FILE *image, int pixel_array_offset, int width, int height) {
}
Run Code Online (Sandbox Code Playgroud)
第一步,为 m 个“struct pixel *”值分配空间。我认为它实际上是为像素值数组分配空间。所以我把
unsigned char **ptrs = height * malloc(sizeof(struct pixel));
Run Code Online (Sandbox Code Playgroud)
对于第二步,我不太明白我应该做什么。我想我需要一个 for 循环来为所有像素数据行分配空间。但我不知道我应该在里面放什么。
for (int i=0, i<height, i++) {
}
Run Code Online (Sandbox Code Playgroud)
既然要分配一个二维数组,首先需要分配一个数组struct pixel *:
struct pixel **ptrs = malloc(height * sizeof(struct pixel*));
Run Code Online (Sandbox Code Playgroud)
这里有几个变化需要注意:
struct pixel,而不是unsigned char。malloc()返回一个指针。将指针乘以整数是无效的。接下来您需要为struct pixel二维数组中的每一行分配一个数组:
for (int i=0, i<height, i++) {
ptrs[i] = malloc(width * sizeof(struct pixel));
}
Run Code Online (Sandbox Code Playgroud)
现在数组已完全分配,您可以用数据填充它:
ptrs[5][6] = { 255, 0, 0}; // a blue pixel
Run Code Online (Sandbox Code Playgroud)
最后记住free()在退出程序之前所有的指针:
for (int i=0, i<height, i++) {
free(ptrs[i]);
}
free(ptrs);
Run Code Online (Sandbox Code Playgroud)