Struct with an array as variable in c

pnizzle picture pnizzle · Sep 17, 2011 · Viewed 14.8k times · Source

i need to create a data type (struct in this case) with an array as a property. I have an initialiser function that initialises this data structure and gives the array a specified size. The problem now is declaring the array in the struct. for example "int values[]" will require that I enter a number in the brackets eg values[256]. Th3 256 should be specified wen the structure is initialised. Is there a way I get around this?

typedef struct 
{
        int values[];      //error here
        int numOfValues;
} Queue;

Answer

raimue picture raimue · Sep 17, 2011

A struct must have a fixed size known at compile time. If you want an array with a variable length, you have to dynamically allocate memory.

typedef struct {
    int *values;
    int numOfValues;
} Queue;

This way you only have the pointer stored in your struct. In the initialization of the struct you assign the pointer to a memory region allocated with malloc:

Queue q;
q.numOfValues = 256;
q.values = malloc(256 * sizeof(int));

Remember to check the return value for a NULL pointer and free() any dynamically allocated memory as soon as it isn't used anymore.