46
Ideas / Weird ideas #2: variable sized structures
« on: June 19, 2014, 02:50:04 AM »
A common idiom in C is something like this:
typedef struct {
int foo_count;
struct foo[0];
} foo_list;
That foo[0] part (GCC syntax, MSVC is foo[]) means "don't allocate any space for this, but let me access the array of elements later". It is heavily used for binary protocols and things where you want array access semantics to the foo elements, but you do not know in advance how many there might be and you are passed a blob of data.
I find the 0 or empty brackets ([]) to be something of a hack. I would prefer a small syntactic change to use foo[...] or something like that. At least to my eye, this means more clearly "we do not know how many there will be at this time".
Note that this is different from a dynamically sized array. For that, you need a hidden count of the actual array size. In fact, the implementation of a dynamic array might very well look like the example above. I am not sure if using the same syntax for both would be a good idea.
Best,
Kyle
typedef struct {
int foo_count;
struct foo[0];
} foo_list;
That foo[0] part (GCC syntax, MSVC is foo[]) means "don't allocate any space for this, but let me access the array of elements later". It is heavily used for binary protocols and things where you want array access semantics to the foo elements, but you do not know in advance how many there might be and you are passed a blob of data.
I find the 0 or empty brackets ([]) to be something of a hack. I would prefer a small syntactic change to use foo[...] or something like that. At least to my eye, this means more clearly "we do not know how many there will be at this time".
Note that this is different from a dynamically sized array. For that, you need a hidden count of the actual array size. In fact, the implementation of a dynamic array might very well look like the example above. I am not sure if using the same syntax for both would be a good idea.
Best,
Kyle