Question about arrays

Adam D. Ruppe destructionator at gmail.com
Wed Jan 22 12:33:54 PST 2014


I think you've got a misunderstanding of what int[] and int[N] 
are. They aren't heap vs stack, they are pointer+length vs memory 
block.

int[50] block;
int[] slice = block[];

The second line does NOT copy the memory: it is more like this in 
C:

int block[50];

// int[] in D is a pointer+length pair so two variables in C:
int* slicePtr = NULL;
size_t sliceLength = 0;

// slice = block[] translates to this:

slicePtr = &block[0];
sliceLength = 50; // this is gotten from the static length


So, when you return slice, you are actually returning a pointer 
to a stack array. The GC doesn't run on it, it is just returning 
from the function means the stack memory gets reused.

Now, the other way:

block = slice[0 .. 50];



A memory block (static array, int[N]) is a value type in D; it is 
just a big block of bytes, not a pointer. So what happens here is:

memcpy(&block, slice.ptr, slice.length);


Contrast that to:

int[] a = slice;

which compiles (conceptually) into:

a.ptr = slice.ptr;
a.length = a.length;



Now, when you do:

int[] a = new int[](50);

what happens is more like:

// new int[](50)
size_t length = 50;
int* ptr = malloc(sizeof(int) * length); // well, GC.malloc in D

// a = the return value of new
a.ptr = ptr;
a.length = length;




Bottom line is assigning or returning slices, without the [] 
syntax, always just returns a pointer+length pair. Assigning or 
returning static arrays (blocks of memory) ALWAYS copies the 
contents.

Doing [] at the end of a block on the right hand side:

int[] a = block[];

is a bit different, since [] on the right hand side means "give 
me a pointer+length combo to block"

And using it on the left hand side forces a copy operation:

a[] = block[]; // copy into a the data pointed to on the right 
hand side



Does this explain it any better?


More information about the Digitalmars-d mailing list