How to represent struct with trailing array member
userABCabc123 via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jan 22 01:42:17 PST 2016
On Friday, 22 January 2016 at 08:39:06 UTC, Dibyendu Majumdar
wrote:
> On Friday, 22 January 2016 at 01:53:53 UTC, Chris Wright wrote:
>> 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];
>>> };
>>>
>> D has bounds checking, which makes this awkward. You would be
>> able to access the data using:
>>
>> struct matrix {
>> int rows, cols;
>> double[] data() {
>> void* p = &this;
>> p += this.sizeof;
>> return (cast(double*)p)[0 .. rows * cols];
>> }
>> }
>>
>
> Right - I should use slices in other words.
>
> Thanks
The basic problem is that double data[1] in D is a static array,
which is not a reference type so if you try to use its .ptr
member you'll encounter many errors because as it is, your struct
is totally POD and it fully resides on the stack.
And the previous answer is erroneous because "p" is declared
nowhere.
struct matrix
{
int rows, cols;
double[] data;
}
or
struct matrix
{
int rows, cols;
double* data;
}
are correct, although you still have to write the boring code to
get the data in sync with rows and cols.
More information about the Digitalmars-d-learn
mailing list