为struct中的内部结构分配变量内存

时间:2014-02-21 08:42:05

标签: c memory-management struct

我有这两种结构:

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;

然后我有一个初始化给定XMP结构的函数:

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

如何为上述struct成员分配内存?

2 个答案:

答案 0 :(得分:2)

您可以尝试以下内容:

image->colors = malloc(image->nof_colors * sizeof *image->colors);
for (..) {
    images->colors[i].code = malloc(..);
}

答案 1 :(得分:0)

使用malloc,您可以将内存分配给颜色

image->colors=(Color *)malloc(image->nof_colors * sizeof(Color);