Translating C "static arrays" into D?

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Feb 26 18:43:41 UTC 2018


On Mon, Feb 26, 2018 at 06:25:42PM +0000, Atila Neves via Digitalmars-d wrote:
[...]
> There's a common misconception in C that arrays and pointers are the
> same thing - they're not. This comes about because of the dubious C
> feature whereby arrays decay into pointers in function calls. Somewhat
> related to this, a little known feature of C is pointers to arrays. In
> your example, that's what y and z are. They have funky syntax and look
> like function pointers, unless they're obscured with a typedef as in
> your example.
> 
> You can pass a double array of any size to x, or a pointer to double,
> but y and z are constrained to be pointers to arrays of size 1.
> Exemplified:
> 
>     typedef double mytype[1];
>     void func1(mytype x);
>     void func2(mytype* x);
> 
>     int main() {
>         double arr1[1];
>         double arr2[2];
>         double* ptr;
> 
>         func1(arr1); // fine
>         func1(arr2); // fine
>         func1(ptr);  // fine
> 
>         func2(&arr1); // fine
>         func2(&arr2); // oops - won't compile
>     }

Ouch.  After working with C for more than 20 years, this one still
escaped me. :-(  How I hate C array semantics...


On Mon, Feb 26, 2018 at 01:33:58PM -0500, Steven Schveighoffer via Digitalmars-d wrote:
[...]
> If you declare mytype as:
> 
> alias mytype = double[1];
> 
> Then you can use it pretty much anywhere. The only exception is when
> it's the exact type of a parameter. In that case, use ref:
> 
> extern(C) void someFunc(ref mytype x, mytype *y, mytype **z);
[...]

Nice, that's also the solution I eventually converged on.


T

-- 
Let's eat some disquits while we format the biskettes.


More information about the Digitalmars-d mailing list