Pointers to Dynamic Arrays

Adam D. Ruppe via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Aug 17 06:42:19 PDT 2015


On Monday, 17 August 2015 at 13:27:19 UTC, Brandon Ragland wrote:
> If that is true, than passing it as _char[] file_ makes the 
> most sense to me. A pointer copy doesn't hurt as bad as an 
> array copy, of say, 100Kibibytes...

Right.

Knowing this helps to explain a lot btw:

char[] foo;

void func(char[] arg) {

}

func(foo);


In that scenario, foo's data is not copied, just a pointer to it 
is. Very fast operation.

arg[0] = 'a';

Since it is a pointer, writing to the arg will also write to foo.

BUT:

arg = "a new thing";

This will NOT be seen outside. It wrote a new pointer to the 
local variable arg's pointer, so now arg and foo point to 
different data.

Similarly:

arg ~= 'a';

will not be seen outside. The pointer might change which is not 
seen outside, and the length will change, which is also not seen.


So char[] arg in D is similar to char* arg_ptr, size_t length_ptr 
in C - changing them inside the function just modifies local 
variables, not the outer variable. Writing *through the pointer 
will be seen outside though since they talk to the same data.




Similarly, slicing in D is just a pointer assignment:

char[] a = b[3 .. 4];

That's like in C:

a.ptr = b.ptr + 3;
a.length = 4-3;


Just basic arithmetic and assignment, no data copy going on.






This is all talking about T[] slices. Static arrays, in the form 
of T[constant], are different:



ubyte[4] static_data;

void slice_test(ubyte[] slice) {}

void static_test(ubyte[4] copy) {}


slice_test(static_data[]); // passes a pointer to the data

static_test(static_data); // passes a copy.




So T[] is always talking about pointer+length, but T[n] is always 
talking about a block of memory which is copied around to other 
T[n].

Putting the [] at the end of it, like I did with slice_test, 
fetches a pointer instead of copying. It is how you convert a 
static memory chunk to a pointer.



There's a few more things but you should understand it now, apply 
the low level principles to it and it all should make sense.

More reading:
http://dlang.org/d-array-article.html
http://dlang.org/arrays.html


More information about the Digitalmars-d-learn mailing list