0

How do you you implement function that takes a pointer int* to a 2D array as an input? My current code is:

#include <iostream>
using namespace std;

int main (void){
  int M [4][4] = {
    {1,2,3,4},
    {5,6,7,8},
    {9,10,11,12},
    {13,14,15,16},
  };
  int* Mat = M;
  myFunc(Mat);
}

void myFunc(int* Matrix)
bhury
  • 1
  • 1

3 Answers3

1

MxN arrays decay to a pointer to the first row (length N). If you want a pointer to the beginning then you need to allow the first row to decay to a pointer to the first element. Also note what @Pete Becker says below.

#include <iostream>

void myFunc(int* Matrix);

int main (void){
  int M [4][4] = {
    {1,2,3,4},
    {5,6,7,8},
    {9,10,11,12},
    {13,14,15,16},
  };

  int* Mat = M[0];
  myFunc(Mat);
}
Brady Dean
  • 3,107
  • 4
  • 24
  • 45
  • **Two** dimensional arrays decay to a pointer to the first row. **Thee** dime signal arrays decay to a pointer to the first two dimensional array. Etc. – Pete Becker Feb 06 '19 at 02:54
0

The answer was quite simple and it only took me like 4 hours (gotta love coding). So take out int* Mat = M[0]; and when calling the function simply recast as (int*)

#include <iostream>

void myFunc(int* Matrix);

int main (void){
  int M [4][4] = {
    {1,2,3,4},
    {5,6,7,8},
    {9,10,11,12},
    {13,14,15,16},
  };

  myFunc((int*)M);
}
bhury
  • 1
  • 1
-2

M pointing to the first row, but its value is the same as pointer to the first element which is M[0][0], so you might change the interpretation for compiler:

int* Mat = reinterpret_cast<int*>(M);
May
  • 99
  • 7
  • 2
    The type of `M` is `int[4][4]` – M.M Feb 06 '19 at 03:03
  • that's not true, do you define a variable like this `int p[4][4] = M;`? this won't even compile. – May Feb 06 '19 at 03:23
  • It is true, the C standard says so. The reason `int p[4][4] = M;` does not compile is that array initializers must be a braced list of initializers for each element – M.M Feb 06 '19 at 05:06