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.

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];
    int x2[64][16];
  • 2
    the compiler must know the second dimension's size. one option is void f(int x[][128],const int m){
    – Juraj
    Commented Aug 2, 2019 at 7:01
  • 1
    I'd rather use one dimensional array. It's not so hard to transform two dimensional indexes to one dimension.
    – KIIV
    Commented Aug 2, 2019 at 8:48

1 Answer 1


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?).

Not the answer you're looking for? Browse other questions tagged or ask your own question.