user198736
user198736

Reputation:

Correct way to allocate memory for structure?

I am trying to determine the best way to allocate memory for a dynamic number of pixels read from a file. I have the number of bytes of pixel data from the header file.

I am trying it in the following way, but am missing something.

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?
}   

Upvotes: 0

Views: 170

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753890

Well, the memory allocation probably doesn't go where you indicated:

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 = ...;
}

The +1 allows for the <= in the for loop. Be careful to check that the <= is correct; it is more usual to use < in a for loop.


For the ..., what if I have the pixels in a char array? How can I step through it and copy into the pixels?

You can do it in either of a couple of ways. Assuming the pixel array is in unsigned char *pixel_array;, then you could use:

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++;
}

or:

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];
}

Just make sure you get the blue, green, red sequence correct.

Upvotes: 2

lulyon
lulyon

Reputation: 7225

Need to allocate memory for pixel before doing something in the for loop.

typedef struct {
    unsigned char blue;
    unsigned char green;
    unsigned char red;
} pixel_t; 
pixel_t *pixel = (pixel_t *)malloc(bmp->dib.bmp_bytesz);
if(pixel == NULL) { exit(-1); }

for(i = 0; i < ((bmp->dib.bmp_bytesz) / 3); i++) {
    // Something here?
    pixel[i].blue = bmp->dib[3 * i];
    pixel[i].green = bmp->dib[3 * i + 1];
    pixel[i].red = bmp->dib[3 * i + 2];
}

Upvotes: 1

Related Questions