Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is &array != &array[0]?

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?)

like image 598
maligree Avatar asked Dec 01 '22 18:12

maligree


2 Answers

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

like image 109
ratchet freak Avatar answered Dec 15 '22 05:12

ratchet freak


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)

like image 33
DejanLekic Avatar answered Dec 15 '22 05:12

DejanLekic