maligree
maligree

Reputation: 6147

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

Upvotes: 4

Views: 222

Answers (3)

kfsone
kfsone

Reputation: 24269

Because "array" used by itself resolves to a pointer to the array, this allows you to treat pointer-to-type and array-of-type somewhat similarly when using structs.

int[] slice = [...];
writeln((cast(void*) slice);
writeln(&slice[0]);

should give you what you want.

Inherited from "C" http://c-faq.com/aryptr/aryptrequiv.html

int[] slice = [...];
int* ptr = &slice[0];

writeln(cast(void*) slice);
writeln(&slice[0]);

// value access
writeln(slice[0]);
writeln(*ptr);
writeln(ptr[0]);

Upvotes: 3

DejanLekic
DejanLekic

Reputation: 19797

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)

Upvotes: 3

ratchet freak
ratchet freak

Reputation: 48216

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

Upvotes: 12

Related Questions