Tuesday, August 17, 2004

Variable sized struct allocation in C

I learnt something today about how to allocate variable sized structures and the use of the FIELD_OFFSET macro in Windows. Here's an example:

One way of defining a variable sized structure is:

typedef struct _VAR_SIZED_STRUCT {
int a;
int b;
char var[1];
} VAR_SIZED_STRUCT, *PVAR_SIZED_STRUCT;

For the sake of example, say the size of the char array needed is 100, you can allocate memory for the structure using the FIELD_OFFSET macro like so:

PVAR_SIZED_STRUCT varStruct = ( PVAR_SIZED_STRUCT) malloc( FIELD_OFFSET( VAR_SIZED_STRUCT, var[100]));

You could also define the char var as a ZERO sized array.

No comments:

Post a Comment