5 ms·
The entire concept of variable-length C arrays is at best iffy, but including them in structs is pretty crazy. Consider these two questions: 1) What is the si
by nknight 15y ago
The entire concept of variable-length C arrays is at best iffy, but including them in structs is pretty crazy.
Consider these two questions:
1) What is the sizeof a struct containing a variable-length array?
2) How do you create an array of structs containing variable-length arrays?
- ori_b 15y ago1) The sum of sizes of the padding and fixed-size members of the struct. In the context of C, this is expected and fairly sane. It also matches the C89 idiom of ending a struct intended with a single element array when you want a variable length array. If C allowed zero-element arrays, then they would be used. /* c89 */ struct { int len; int vla[1]; /* really len elements long */ } MyVLAStruct; 2) Carefully.
- nknight 15y ago> 2) Carefully. Can you provide code demonstrating how you will "carefully" create a C array of structs with a variable-sized member? It will be very educational for me, at least, and I think others, as well.
- ori_b 15y agoWell, in the normal case, you wouldn't do it. These variable length structures need to be created on the heap to be able to be used in a variable length way, for the most part, so you'd just put a pointer to them into an array. However, I can think of a couple of methods, such as packing into an array, and using a second one to index it, like so: a = [aaaa,bb,ccc,dd] idx = [0,4,6,9] To get to the i'th element of a, accesses would go through idx like so: a[idx[i]]. In general, of course, there's no way to allow O(1) access and updates without occasional repacking.
- nknight 15y agoThis is exactly the problem I'm getting at, you're not actually working within the confines of C here, you're creating funny workarounds for the fact that certain C features don't work how you want them to, and you're violating the type system in the process. The concept of VLAs does not fit the language well, they're inherently something of an anomaly. Allowing them in structs would simply multiply the anomalies. I'm frankly shocked that they were codified in C99 at all, rather than codifying something akin to alloca() with implementation-defined behavior, but I'm infinitely grateful the committee did not elect to make them anything more than they are -- which is a semi-portable mechanism for allocating arbitrary amounts of automatic memory.