假设我们的位图图像高度为M,宽度为N。在此实验中,我们将始终假设宽度N是4的倍数,这简化了文件中的字节布局。对于此图像,像素数组以以下方式精确地存储3 x N x M字节:
每组3个字节表示一个像素,其中字节按顺序存储像素的蓝色、绿色和红色值。
像素按行分组。例如,像素数组中前3 x N个字节表示图像最上面一行的像素。
pixel_array_offset
是像素数组开始的位置。
给出如下struct pixel
:
struct pixel {
unsigned char blue;
unsigned char green;
unsigned char red;
};
以下是实现该功能的要求:
/*
* 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) {
}
首先,为m个"struct pixel *"值分配空间。我认为它实际上是为像素值数组分配空间。因此我放置了:
unsigned char **ptrs = height * malloc(sizeof(struct pixel));
对于第二步,我不太明白我应该做什么。我认为我需要一个for循环来为所有像素数据的行分配空间。但是我不知道里面应该放什么。
for (int i=0, i<height, i++) {
}
m "struct pixel *"
分配空间。m x struct pixel *
如何变成unsigned char **ptrs
?也许是struct pixel **ptrs
?(现在从技术上讲,由于指针就是指针就是指针,而且它是一个char
类型,所以你不会违反严格别名规则,因此你很幸运)。 - David C. Rankin