Does D actually support flexible array members?

Krzysztof Jajeśnica krzysztof.jajesnica at gmail.com
Thu Aug 18 09:48:48 UTC 2022


No, D does not support flexible array members or dynamically 
sized structs.

`char[]` is a D slice, which is NOT equivalent to a C array.
A slice is basically a pointer+length pair:
```d
// you can't actually name a struct `char[]`, it's just for 
explanation purposes
struct char[] {
     char* ptr; //pointer to first element
     size_t length;
}
```

Also the allocation code probably only worked by accident and 
will likely cause memory corruption:
```d
void* result = cast(void*)(&ar.currChunk.memory + ar.currInd);
```
`&ar.currChunk.memory` doesn't give you a pointer to the first 
slice element - it gives you a pointer to the slice itself (the 
`char[]` "struct"). To get a pointer to the first element you can 
use `ar.currChunk.memory.ptr`, although since the end goal is to 
get a pointer to the `ar.currInd` element it's preferable to 
replace the entire line with this:
```d
void* result = &ar.currChunk.memory[ar.currInd];
```
(this way you get bounds checking on slice indexing so you can't 
get a pointer past the last element of the slice).

Also `void[]` is a more appropriate type for a raw memory array 
than `char[]` (`char[]` in D is used almost exclusively as 
"mutable string", and depending on the implementation the garbage 
collector may not scan `char[]` elements for pointers).


More information about the Digitalmars-d-learn mailing list