This is probably a stupid question, but I don’t understand why this works:
int** test = new int*[7];
int x = 7;
*(test+1) = &x;
cout << (**(test+1));
test is a pointer to a pointer right? The second pointer points to the array, right?
In my understand I would need to dereference the “test” pointer first to get to the pointer that has the array.
(*test) // Now I have int*
*((*test) + 1) // to access the first element.
Where is my faulty thinking?
Is your misunderstanding that you think you have created a pointer to an array of
7int? You haven’t. You actually have created an array of7pointers 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
*testyou get that first pointer which you haven’t initialized yet, though. If you would add1to that, you would add1to some random address. But if you add1totestyou 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
Without using the typedef, this looks like the following
That is, you have created a one-element array, where the element-type of that is a 7-element array of int.
newgives 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.