Does D actually support flexible array members?

Paul Backus snarwin at gmail.com
Thu Aug 18 11:25:22 UTC 2022


On Thursday, 18 August 2022 at 08:41:02 UTC, LinguisticMystic 
wrote:
> I'm porting some C code for arena allocator to D, and somehow 
> the flexible array members (a feature of C99 for 
> dynamically-sized structs) work in D without significant 
> changes in the code. Here's my arena definition:
>
> ```
> struct ArenaChunk {
>     size_t size;
>     ArenaChunk* next;
>     char[] memory; // flexible array member
> }
>
> struct Arena {
>     ArenaChunk* firstChunk;
>     ArenaChunk* currChunk;
>     int currInd;
> }
> ```
>
> And here's how I use the FAM's memory for allocating stuff:
>
> ```
>     void* result = cast(void*)(&ar.currChunk.memory + 
> ar.currInd);
> ```

I think the closest way to approximate this in D is to use a 
zero-length static array:

```d
struct ArenaChunk {
     size_t size;
     ArenaChunk* next;
     char[0] memory;
}
```

Then your usage example becomes

```
     void* result = cast(void*)(ar.currChunk.memory.ptr + 
ar.currInd);
```

Note that in D you must use `.ptr` to get a pointer to the 
array's first element; it does not decay automatically like in C.


More information about the Digitalmars-d-learn mailing list