In C:
int a[10];
printf("%p\n", a);
printf("%p\n", &a[0]);
Yields:
0x7fff5606c600
0x7fff5606c600
Which is what I expect. Now, in D, I'm trying this (obviously no use case, just fooling around):
int[] slice = [...];
writeln(&slice);
writeln(&slice[0]);
Yields:
7FFF51600360
10E6E9FE0
Why the difference? Looks like a completely different memory segment. (Though it just occurred to me that perhaps arrays in D aren't just adjacently allocated ints?)
in D an array is essentially a struct with a pointer and a length field and is treated as such
to get the address to the first element you can query the ptr field
It is simple - dynamic D arrays are not the same as C arrays. Dynamic D arrays hold the length of the array, while C arrays do not. As such dynamic D arrays do not rely on a NULL to mark the end of the array. As Adam points out in his comment, static D arrays behave the same as C arrays.
import std.stdio;
int main() {
// static array
int[10] sarr;
writeln(sarr.length);
writeln(&sarr);
writeln(&sarr[0]);
// dynamic array
int[] darr = [1, 2, 3];
writeln(darr.length);
writeln(&darr);
writeln(&darr[0]);
// These are all the same
writeln(darr.ptr);
writeln(cast(void*) darr);
writeln(&darr[0]);
return 0;
}
(DPaste link: http://dpaste.dzfl.pl/f708d945)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With