Question about arrays
Andrej Mitrovic
andrej.mitrovich at gmail.com
Sat Apr 21 15:27:40 PDT 2012
On 4/22/12, Stephen Jones <siwenjo at gmail.com> wrote:
> My C programming lies in cobwebs but from memory an array was a
> pointer to the zeroth index of a set of uniformly sized chunks of
> memory. I am perplexed to find that in D a call to an array (of
> float vertices for example) cannot be accomplished by handing &v
> to functions that need the zeroth index. Is this because D holds
> a pointer to an array object and the zeroth index is accessed
> (via compiler background work) to &v[0]?
>
D array -> struct of a length and pointer to the first element.
If you want to pass arrays to C functions you can do either of these:
float[] arr;
cFunc(arr.ptr, arr.length)
cFunc(&arr[0], arr.length);
I'm assuming the C function needs a length. Maybe this will make things clearer:
void main()
{
int[] a = new int[](10);
size_t count = *cast(size_t*)&a; // first element is the count
assert(count == 10);
a[0] = 5;
a[1] = 100;
int* iter = &a[0]; // or use a.ptr
assert(*iter == 5);
++iter;
assert(*iter == 100);
}
Of course you wouldn't really use this style of code in D, but if you
have to pass arrays to C use the .ptr field or &arr[0]. On the other
hand, passing jagged multidimensional arrays via .ptr to C functions
isn't going to work out of the box, but that's another topic (and
there's a workaround).
A good article about D arrays/slices is here:
http://dlang.org/d-array-article.html
More information about the Digitalmars-d-learn
mailing list