Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a fixed struct header for variable sized array

I am looking to create a fixed size struct header for variable sized array in the D programming language.. In "C" one would place a zero length or empty bracket Array as the last item declared within the fixed struct header, and then adjust ones call to Malloc, to include the additional storage required by the variable sized part of the data structure, who's first element would be referenced by this last declaration.

But in the D language an Array is a more advanced object, and As I'm attempting to build up a set of structured Opcode strings, I really want to express a compound struct with a trailing memory reference as it's final item ( the first element of the array that follows..

How does one declare / create / work with a compound variable length memory structure when using the D programming language?

like image 764
Peter Li Avatar asked Sep 21 '26 21:09

Peter Li


1 Answers

it's the exact same way as you would in c

struct VarArray(T){
uint length;
T[0] t;

static VarArray!T* allocate(T)(uint length){
VarArray!T* ret = enforce(malloc((VarArray!T).sizeof+T.sizeof*length));
*ret.length=length;
return ret;
}

}

check http://dlang.org/arrays.html#static-arrays:

A static array with a dimension of 0 is allowed, but no space is allocated for it. It's useful as the last member of a variable length struct, or as the degenerate case of a template expansion.

like image 167
ratchet freak Avatar answered Sep 23 '26 16:09

ratchet freak