Is your misunderstanding that you think you have created a pointer to an array of 7
int? You haven't. You actually have created an array of 7
pointers to int. So there is no "second pointer" here that would point to an array. There is just one pointer that points to the first of the 7 pointers (test
).
And with *test
you get that first pointer which you haven't initialized yet, though. If you would add 1
to that, you would add 1
to some random address. But if you add 1
to test
you get a pointer that points to the second pointer of the array. And dererencing that you get that second pointer, which you did initialize.
What you describe would be achieved by a different syntax
typedef int array[7];
array* test = new int[1][7];
// Note: "test" is a pointer to an array of int.
// There are already 7 integers! You cannot make it
// point to an int somehow.
*(*test + 1) = 7;
int *p1 = *test
int i1 = *(p1 + 1); // i1 is 7, second element of the int[7]
delete[] test;
Without using the typedef, this looks like the following
int(*test)[7] = new int[1][7];
That is, you have created a one-element array, where the element-type of that is a 7-element array of int. new
gives you a pointer back to that array. Note that the parenthesis is important: The *
has less precedence than the [7]
, so otherwise this would be taken as an array of 7 pointer to integers.