Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct with an array as variable in c

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;
like image 339
pnizzle Avatar asked Nov 27 '22 12:11

pnizzle


2 Answers

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.

like image 70
raimue Avatar answered Dec 16 '22 10:12

raimue


#include<stdio.h> 
#include<stdlib.h>
typedef struct Queue {
int numOfValues;
int values[0]; 
} Queue_t;

int main(int argc, char **argv) {
Queue_t *queue = malloc(sizeof(Queue_t) + 256*sizeof(int));
return (1);
}

This way you can declare 'variable length arrays'. And you can access your array 'values' with queue->values[index]

EDIT: Off course you need to make sure that once you free you take into account the 'n*sizeof(int)' you have allocated along with sizeof(Queue_t) where n=256 in the above example HTH

like image 43
Anoop Menon Avatar answered Dec 16 '22 10:12

Anoop Menon