c - Correct way to allocate memory for structure? -
i trying determine best way allocate memory dynamic number of pixels read file. have number of bytes of pixel data header file.
i trying in following way, missing something.
typedef struct { unsigned char blue; unsigned char green; unsigned char red; } pixel_t; for(i = 0; <= ((bmp->dib.bmp_bytesz) / 3); i++) { // here? }
well, memory allocation doesn't go indicated:
pixel_t *pixels = malloc(((bmp->dib.bmp_bytesz/3)+1) * sizeof(*pixels)); if (pixels == 0) ...deal out of memory error... (int = 0; <= bmp->dib.dmp_bytesz/3; i++) { pixels[i].blue = ...; pixels[i].green = ...; pixels[i].red = ...; }
the +1
allows <=
in for
loop. careful check <=
correct; more usual use <
in for
loop.
for
...
, if have pixels inchar
array? how can step through , copy pixels?
you can in either of couple of ways. assuming pixel array in unsigned char *pixel_array;
, use:
unsigned char *p = pixel_array; (int = 0; <= bmp->dib.dmp_bytesz/3; i++) { pixels[i].blue = *p++; pixels[i].green = *p++; pixels[i].red = *p++; }
or:
for (int = 0; <= 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]; }
just make sure blue, green, red sequence correct.
Comments
Post a Comment