Implicit dereferencing

Steven Schveighoffer schveiguy at yahoo.com
Mon Apr 1 19:52:47 PDT 2013


On Mon, 01 Apr 2013 20:07:30 -0400, Luís Marques <luismarques at gmail.com>  
wrote:

> Consider this (non-portable) code:
>
> {
>      int[2] a;
>      int[2] b;
>      int[2] *c;
>      c = &a;
>
>      c[0] = 7;
>      assert(a[0] == 7); // OK, as expected
>
>      c[1] = 42;
>      assert(b[0] == 42); // do we really want this semantics?
> }
>
> Because indexing c automatically dereferences the pointer, "c[0] = 7"  
> assigns to a[0], as expected. This is the same as "(*c)[0] = 7", which  
> is useful.

This is not what is happening.  If you add:

writeln(a);

you will see:
7, 7

You see, indexing does NOT dereference the pointer, it's an index for that  
pointer.  c[0] means *(c + 0).  A pointer is essentially an unchecked  
slice, with undefined length.  This is how it works in C also.

c[1] is the same as *(c + 1), completely consistent (and also sets b to  
42, 42)

-Steve


More information about the Digitalmars-d mailing list