我正在尝试确定为从文件中读取的动态像素数分配内存的最佳方式。我有来自头文件的像素数据的字节数。
我正在按以下方式尝试,但遗漏了一些东西。
typedef struct {
unsigned char blue;
unsigned char green;
unsigned char red;
} pixel_t;
for(i = 0; i <= ((bmp->dib.bmp_bytesz) / 3); i++) {
// Something here?
}
最佳答案
好吧,内存分配可能没有按照您指定的方式进行:
pixel_t *pixels = malloc(((bmp->dib.bmp_bytesz/3)+1) * sizeof(*pixels));
if (pixels == 0)
...deal with out of memory error...
for (int i = 0; i <= bmp->dib.dmp_bytesz/3; i++)
{
pixels[i].blue = ...;
pixels[i].green = ...;
pixels[i].red = ...;
}
+1
允许 <=
在for
环形。小心检查 <=
是正确的;通常使用 <
在for
循环。
For the
...
, what if I have the pixels in achar
array? How can I step through it and copy into the pixels?
您可以通过两种方式中的任何一种来完成。假设像素数组在 unsigned char *pixel_array;
中,那么你可以使用:
unsigned char *p = pixel_array;
for (int i = 0; i <= bmp->dib.dmp_bytesz/3; i++)
{
pixels[i].blue = *p++;
pixels[i].green = *p++;
pixels[i].red = *p++;
}
或:
for (int i = 0; i <= bmp->dib.dmp_bytesz/3; i++)
{
pixels[i].blue = pixel_array[i*3+0];
pixels[i].green = pixel_array[i*3+1];
pixels[i].red = pixel_array[i*3+2];
}
只需确保蓝、绿、红顺序正确即可。
关于为结构分配内存的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17713377/