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
  • 2
    check this : https://stackoverflow.com/questions/8617466/a-pointer-to-2d-array – asn Feb 06 '19 at 02:07
  • 2
    What is the question? – Water Feb 06 '19 at 02:11
  • 1
    I, too, cannot tell what you are asking. A question typically contains a question mark. – Richard Feb 06 '19 at 02:13
  • 2
    "I am currently working on a C++ function that I am working on" is probably this month's best. – bipll Feb 06 '19 at 02:42
  • You must have been given some description of what the argument is supposed to be. (My guess is that you're expected to store your data in a one-dimensional array and compute the one-dimensional index from the two-dimensional ones.) – molbdnilo Feb 06 '19 at 03:25
  • You can't pass `M` as `int*`, you can pass a row of `M`, but not the entire `M`. – David C. Rankin Feb 06 '19 at 05:37

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,378
  • 5
  • 24
  • 50
  • **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
  • 101
  • 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