2

Analyzing this and this answers under Arduino, which should be the proper way to pass a 2D array into a function?

The function should be applicable to different sizes of 2D arrays.

// NOT COMPILING EXAMPLE
void f(int** x,const int m, const int n){
// access x as x[0][0], x[0][1], etc...
}

void main{}{
    int x1[16][128];
    f(x1,16,128);
    int x2[64][16];
    f(x2,64,16);
}
Brethlosze
  • 337
  • 1
  • 4
  • 17

1 Answers1

2

According the prototype of f and the usage pattern for its x argument, the function expects this argument to be a pointer to the first element of an array of pointers to the first elements of arrays of int. However, the matrix in main() is defined as an array of arrays of int. If you try to pass this to a function, the matrix will decay into a pointer to an array of int. That's not what you want.

If you want both dimensions of the matrix to be variable, the only simple solution I see is to build an extra array of pointers (pointing to the matrix rows) and pass that array to the function

int main() {
    int x[16][128];

    // Build an array of pointers to rows.
    int *px[16];
    for (int i = 0; i < 16; i++)
        px[i] = x[i];

    f(px, 16, 128);
}

For more information on this, see the section Arrays and Pointers in the C FAQ, and more specifically the questions 6.16 (How can I dynamically allocate a multidimensional array?) and 6.19 (How do I write functions which accept two-dimensional arrays when the width is not known at compile time?).

Edgar Bonet
  • 45,094
  • 4
  • 42
  • 81