Changing values in an array from a pointer?
arrays, c++, iostream, pointers
Solution
I have to do `a[0][0]` as if a was an array of arrays.
Indeed, `a` is a pointer to an array, so the array itself is `*a`, and the first element of the array would be `(*a)[0]` or, equivalently, `a[0][0]`.
You probably want `a` to be a pointer to the first element of the array (just as `c` is a pointer to the first element of a dynamic array):
int * a = b;
and now `a[i]` will be element `i` of the array as expected.
Problem
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