0

I have these two structs:

typedef struct {
    unsigned char r, g, b; // color components
    char *code; // color code (char combination)
} Color;


typedef struct {
    unsigned int width; // in pixels
    unsigned int height; // in pixels
    unsigned char cpp; // chars per pixel
    unsigned int nof_colors; // number of colors
    Color *colors; // reference to Color struct table
    unsigned int *data[]; // holds `width` x `height` entries for `colors` codes
} XPM;

I then have a function that initializes a given XMP struct:

void initXPM(XPM *image, unsigned int width, unsigned int height, 
             unsigned char cpp, unsigned int nof_colors) {
    image.colors = [allocate memory for `nof_colors` Colors, 
                    with each color having the length of `code` exactly `cpp`]
}

How can I allocate memory for the above struct member?

linkyndy
  • 17,038
  • 20
  • 114
  • 194

2 Answers2

2

You can try something like:

image->colors = malloc(image->nof_colors * sizeof *image->colors);
for (..) {
    images->colors[i].code = malloc(..);
}
cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • `sizeof *image->colors` doesn't depend on how large the `Color` struct is (and which you defined after)? – linkyndy Feb 21 '14 at 08:47
  • @AndreiHorak It's a well-known idiom. `sizeof` only cares about the type of `image->colors`, it doesn't dereference it or anything. – cnicutar Feb 21 '14 at 08:48
  • And since the size of `image->colors`'s type can change based on its `code` length, does it allocate the correct amount of memory to `image->colors` even though at that point the size of the `Color` struct is not known? – linkyndy Feb 21 '14 at 08:52
  • 1
    @AndreiHorak In your code the size of `Color` is known: **its size does not depend on what you assign to `code`**. – cnicutar Feb 21 '14 at 08:53
  • 1
    To complete @cnicutar comment: the size of `Color` is 3 chars + a **pointer** : it does not matter how long is the pointed data, it is still an address that you keep in your allocated structure. – n0p Feb 21 '14 at 10:26
  • Thank you very much for clarifying and for helping! – linkyndy Feb 21 '14 at 17:33
0

Using malloc you can allocate the memory to colors

image->colors=(Color *)malloc(image->nof_colors * sizeof(Color);
Devavrata
  • 1,785
  • 17
  • 30