zztops
zztops

Reputation: 714

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;

Upvotes: 3

Views: 215

Answers (2)

Ioan
Ioan

Reputation: 2412

Yes, you can. If you use C99, there's flexible array members. Otherwise, you can do what Microsoft does. Take your original structure definition and map it to an existing block of memory. Reassign the pointer to point just after the structure definition.

Also, the MS approach would allow multiple members with variable size; you just need to properly update each pointer.

(Note: The "MS approach" is just something encountered often in Windows APIs; I don't know if there's an actual term for the practice.)

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 225032

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;

Upvotes: 5

Related Questions