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 开发者_JS百科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;
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.
#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
You can use C99 features like VLA, e.g.
int main()
{
int len=1234;
struct MyStruct {int i,array[len];} var;
var.array[0]=-1;
var.array[len-1]=1;
printf( "%i %i %lu", var.array[0],var.array[len-1],(unsigned long)sizeof(var) );
return 0;
}
精彩评论