Accessing array elements with a pointer-to-array

Sergey kornburn at yandex.ru
Thu Jan 25 20:28:37 UTC 2024


On Thursday, 25 January 2024 at 20:11:05 UTC, Stephen Tashiro 
wrote:
> Can the elements of an array be accessed with a pointer using 
> the usual indexing notation (e.g."[2][0]") for array elements? 
> - or must we treat the elements associated with the pointer as 
> 1-dimensional list and use pointer arithmetic?
>
> A more elementary question is why array index 2 is 
> out-of-bounds in the following
> code, which won't compile:
>

Be aware of the different dimension size of static and dynamic 
arrays

```d
void main()
{
     import std;

     ulong [3][2] static_array = [ [0,1,2],[3,4,5] ];
     ulong [][] dynamic_array;

     ulong *pointer;
     ulong[]* dpointer;

     dynamic_array = new ulong[][](3,2);

     static_array[1][1] = 6;
     dynamic_array[2][1] = 6;

     writeln(static_array);
     pointer = static_array.ptr.ptr;
     writef("*pointer[1][1] = %d\n", *(pointer+4));

     writeln(dynamic_array);
     dpointer = dynamic_array.ptr;
     writef("*pointer[2][1] = %d\n", dpointer[2][1]);
}
```



More information about the Digitalmars-d-learn mailing list