Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically allocate C struct?

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?

like image 512
pf. Avatar asked Dec 30 '09 12:12

pf.


1 Answers

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.

like image 88
spurserh Avatar answered Sep 17 '22 20:09

spurserh