I've been playing around with pointers to help get a better understanding. I have declared a as a pointer to an array of integers of length 3 and b as an array of integers of length 3. I then point a at b.
int main()
{
int (*a)[3];
int b[3] { 2, 4, 6 };
a = &b;
a[0][0] = 8;
// This prints out 8 and 8.
std::cout << a[0][0] << "\t" << b[0];
// This prints out 0x28fecc and 8.
std::cout << a[0] << "\t" << b[0];
return 0;
}
To access an element of b through the pointer a, I have to do a[0][0] as if a were an array of arrays. This is compared to declaring a pointer to an array of integers using the new keyword where I can just output c[0].
int* c = new int[3] { 2, 4, 6 };
std::cout << c[0];
Why is this?
Many thanks, George
int(or whatever), so you need different syntax to access the array elements through it.int (*a)[3];, just walk away from the keyboard for a while, repeat "I'm writing C++ not C, so I don't need to do ugly things like that." about a dozen times, and only when you've convinced yourself that simplicity is good, come back and write what you really wanted to (which I'm quite certain will be something different from that).cis a pointer tointbecause this says so:int* c, independently of what is on the RHS of the initialization.newreturns pointer to an array (or the first element), and arrays themselves decay into pointers to their first element under many circumstances. Fortunately you don't really have to deal with this kind of stuff in modern C++.