How to represent struct with trailing array member

Chris Wright via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jan 21 17:53:53 PST 2016


On Thu, 21 Jan 2016 21:52:06 +0000, Dibyendu Majumdar wrote:

> Hi
> 
> I have C code where the struct has a trailing array member:
> 
> struct matrix {
>    int rows;
>    int cols;
>    double data[1];
> };
> 
> In C code this is allocated dynamically to be variable size. The array
> is used just as normal.
> 
> How should this be translated to D? Will D's array access allow data
> elements to be accessed beyond the size declared?
> 
> Thanks and Regards Dibyendu

D has bounds checking, which makes this awkward. You would be able to 
access the data using:

  double a = matrix.data.ptr[7];

The .ptr property is just a pointer to the first element of the array, 
and pointer indexing doesn't have bounds checking.

A safer way of doing this is:

  struct matrix {
    int rows, cols;
    double[] data() {
      void* p = &this;
      p += this.sizeof;
      return (cast(double*)p)[0 .. rows * cols];
    }
  }

You must still take responsibility for allocating variables like this, 
but if you've done it in C, you're used to that.

Furthermore, if you're using the GC, allocate memory as void[] if there's 
a possibility that the data will contain pointers. If you allocate, for 
instance, ubyte[] instead, the GC will assume no pointers. That means it 
can collect things that only have a pointer hidden in the ubyte[].


More information about the Digitalmars-d-learn mailing list