Here's a little program I'm building while I try to figure out how to access multidimensional arrays with a pointer. Essentially, I'm trying to build a square "world", created by and intended to be manipulated by functions. Here's the problem I'm running into.
// evolution.cpp
#include <iostream>
usingnamespace std;
int *initWorld(int *orig, int m, int n);
int main()
{
int worldHeight = 10;
int worldWidth = 10;
int world[worldHeight][worldWidth];
int *arr = world[0];
arr = initWorld(arr, worldHeight, worldWidth);
for(int a = 0; a < worldHeight; a++)
for(int b = 0; b < worldWidth; b++)
cout << world[a-1][b-1] << " ";
int test;
cin >> test;
return 0;
}
int *initWorld(int *orig, int worldHeight, int worldWidth)
{
for(int i = 0; i < worldHeight; i++)
{
orig[i] = 0;
cout << "this is " << orig[i] << endl;
}
return orig;
}
I figured out how to initialize the pointer to point to the multidimensional array:
1 2
int *arr = world[0];
arr = initWorld(arr, worldHeight, worldWidth);
My problem is once I pass it to the function, I don't know how to change anything other than [x][0].
1 2 3 4 5 6 7 8 9
int *initWorld(int *orig, int worldHeight, int worldWidth)
{
for(int i = 0; i < worldHeight; i++)
{
orig[i] = 0;
cout << "this is " << orig[i] << endl;
}
return orig;
}
I can access orig[0] to orig[10000], but this is only the first element in every row. How do I change my function to be able to select both the X and Y elements of my matrix to be changed? Thanks in advance.
The compiler shouldn't allow non-constant dimensions. Some allow this but it is not standard C++ and some compilers do not allow it, also meaning that it's not flexible. Use this instead: int *world = newint[worldHeight][worldWidth];
G++ allows it because it's part of C99, but variable sized arrays are definitely not standard C++. If you need to determine the size of an array at runtime, you need to dynamically allocate them using pointers and the new keyword, like computerquip shows above me.
Don't forget to delete[] any arrays you are done with.