translate C struct char array into D
Paul Backus
snarwin at gmail.com
Fri Jul 30 14:40:17 UTC 2021
On Friday, 30 July 2021 at 14:05:58 UTC, workman wrote:
> I get want to define this struct in D:
>
> ```c
> struct test1 {
> struct test1 *prev;
> struct test1 *next;
> size_t v1;
> size_t v2;
> size_t v3;
> char data[];
> };
> ```
>
> ```d
> struct test1 {
> test1 *prev;
> test1 *next;
> size_t v1;
> size_t v2;
> size_t v3;
> char* data;
> };
> ```
>
> when I compare the size, test1.sizeof is 48 and sizeof(struct
> test1) from C is 40.
>
> Anyone can explain what should I do with this ?
>
> If I use test1 as member of other struct, the total size will
> not match.
`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
More information about the Digitalmars-d-learn
mailing list