Dynamically allocate C struct?

pf. picture pf. · Dec 30, 2009 · Viewed 30k times · Source

I want to dynamically allocate a C struct:

typedef struct {
    short *offset;
    char *values;
} swc;

Both 'offset' and 'values' are supposed to be arrays, but their size is unknown until runtime.

How can I dynamically allocate memory for my struct and the struct's arrays?

Answer

spurserh picture spurserh · Dec 30, 2009
swc *a = (swc*)malloc(sizeof(swc));
a->offset = (short*)malloc(sizeof(short)*n);
a->values = (char*)malloc(sizeof(char)*n);

Where n = the number of items in each array and a is the address of the newly allocated data structure. Don't forget to free() offsets and values before free()'ing a.