translate C struct char array into D

Paul Backus snarwin at gmail.com
Fri Jul 30 16:45:07 UTC 2021


On Friday, 30 July 2021 at 15:51:12 UTC, Tejas wrote:
> On Friday, 30 July 2021 at 14:40:17 UTC, Paul Backus wrote:
>> On Friday, 30 July 2021 at 14:05:58 UTC, workman wrote:
>>> [...]
>>
>> `char data[]` in the C struct is not a pointer, but actually a 
>> [C99 flexible array member][1], and does not count towards the 
>> struct's `sizeof`.
>>
>> D does not have flexible array members, but you can simulate 
>> one using a struct method:
>>
>> ```d
>> struct test1 {
>>     // member variables...
>>
>>     char* data() {
>>         return cast(char*) (&this + 1);
>>     }
>> }
>> ```
>>
>> [1]: http://port70.net/~nsz/c/c99/n1256.html#6.7.2.1p16
>
> By the way how is this safe? And how exactly are we even 
> assigning the data to a variable/reference in this case? Can 
> you please show an example demonstrating this?

In order to use a flexible array member, you have to allocate 
extra memory beyond the end of the struct, and it's entirely your 
responsibility to ensure that you do not go out-of-bounds when 
accessing that memory.


More information about the Digitalmars-d-learn mailing list