What do we assign to my_array
here?
You can assign an int*
to the elements of my_array
. E.g.
my_array[0] = new int[20];
or
int i;
my_array[0] = &i;
my_array
is a pointer that points to what?
It points to an an array of 10 int*
objects.
Is there any way to iterate through my_array
(the pointer) and set up a two-dimensional array of integers (and not int*)?
Not sure what you are expecting to see here. An element of my_array
can only be an int*
.
If you want my_array
to be a pointer to a 2D array, you may use:
int (*my_array)[20] = new int[10][20];
Now you can use my_array[0][0]
through my_array[9][19]
.
PS If this is your attempt to understand pointers and arrays, it's all good. If you are trying to deploy this code in a working program, don't use raw arrays any more. Use std::vector
or std::array
.
For a 1D array, use:
// A 1D array with 10 elements.
std::vector<int> arr1(10);
For a 2D array, use:
// A 2D array with 10x20 elements.
std::vector<std::vector<int>> arr2(10, std::vector<int>(20));