# pointer to matrix

• 01-02-2007
TriKri
pointer to matrix
I have two different twodimensional matrixes of the same size

Code:

```Square Matrix1[MTR_WIDTH][MTR_HEIGHT]; Square Matrix2[MTR_WIDTH][MTR_HEIGHT];```
Now I am only using one of them at a time, the other serves as a storage matrix in the mean time. So I wan't to have a pointer pointing to the one currently in use. I have tried this:

Code:

`Square *CurrentMatrix[MTR_WIDTH][MTR_HEIGHT] = Matrix1;`
But it doesn't work, "conflicting declaration 'Square*CurrentMatrix[160][120]' ".

I have tried some different ways but can't figure out how to write it. Can someone help me please?
• 01-02-2007
anon
Something like this is possible.

Code:

```#include <iostream> const int W = 2; const int H = 2; void print(int* array) {     for (int i = 0; i < W; i++) {         for (int j = 0; j < H; j++) {             std::cout << *array++ << " ";         }     std::cout << std::endl;     } } int main() {     int a[W][H] = {{33, 34}, {35, 36}};     int b[W][H] = {{100, 110}, {120, 130}};     int* c;     c = &a[0][0];     print(c);     c = &b[0][0];     print(c);     std::cin.get(); }```
In your case you would need a Square pointer initialized to the first element in the 2D array. It is your responsibility to know, how many Squares you may access with this pointer (MTR_WIDTH*MTR_HEIGHT) using pointer arithmetics.

(By the way, you can pass 2D arrays to functions as well if you changed the signature. Then you wouldn't need c at all.)
• 01-02-2007
vart
You can also use pointer to array
Code:

``` #include <iostream> const int W = 2; void print(int(* array)[W],int height) {     for (int i = 0; i < W; i++)     {         for (int j = 0; j < height; j++)         {             std::cout << array[i][j] << " ";         }         std::cout << std::endl;     } } int main() {     const int H = 2;     int a[W][H] = {{33, 34}, {35, 36}};     int b[W][H] = {{100, 110}, {120, 130}};     int(* c)[W];     c = a;     print(c,H);     c = b;     print(c,H);     std::cin.get();     return 0; }```
• 01-02-2007
hardi
Maybe only Square** pointer_to_current_2d_array; will do the trick :)
you could evaluate it like this: pointer_to_current_2d_array = &Matrix1;

Imho it should work.
• 01-02-2007
vart
Quote:

Originally Posted by hardi
Maybe only Square** pointer_to_current_2d_array; will do the trick :)
you could evaluate it like this: pointer_to_current_2d_array = &Matrix1;

Imho it should work.

I think you should try to compile it before suggesting
• 01-03-2007
hardi
didn't work
Quote:

Originally Posted by vart
I think you should try to compile it before suggesting

yep, It didn't work. sorry
• 01-03-2007
TriKri
Thanks vart! It worked perfectly fine. I solved it like this:

Code:

```Square Matrix1[MTR_WIDTH][MTR_HEIGHT]; Square Matrix2[MTR_WIDTH][MTR_HEIGHT]; Square (*CurrentMatrix)[MTR_HEIGHT] = Matrix1;```
Also anon's way worked, but it was a little bit more complicated in that case.