Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a struct whose size is not known at compile time?

As the question states I am looking to create a struct in C whose total size I do not know at compile time.

For example, I would like to create a struct that contains a count value and an array with count elements. I know this could be implemented as:

typedef struct myStruct{
    int count;
    int *myArray;
} myStruct;

However, I want this struct to take up one solid block of memory so I could use memcpy() on it at a later point in time. Like this:

typedef struct myStruct{
    int count;
    int myArray[count];
} myStruct;
like image 852
zztops Avatar asked Jan 18 '26 16:01

zztops


1 Answers

It sounds like you're looking for flexible array members:

typedef struct myStruct
{
    int count;
    int myArray[];
} myStruct;

Then, when you allocate it later:

myStruct *x = malloc(sizeof(myStruct) + n * sizeof(int));
x->count = n;
like image 127
Carl Norum Avatar answered Jan 20 '26 07:01

Carl Norum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!