-1

I want to pass a 2D const array using a double pointer but I get a compiler error.

const unsigned char sizex=2;
const unsigned char sizey=5;
const unsigned char arr[sizex][sizey] ={
  {1,2,3,4,5},
  {6,7,8,9,10}};

void foo (const unsigned char **a, const unsigned char x, const unsigned char y) {
  int i,j;
  for(i=0;i<x;i++) {
    for(j=0;j<y;j++) {
      Serial.println(a[i][j]);
    }
  }
}

void main() {
  foo(arr,sizex,sizey);
}

Error

cannot convert 'const unsigned char (*)[5]' to 'const unsigned char**' for argument '1' to 'void foo(const unsigned char**, unsigned char, unsigned char)'

void foo (const unsigned char a,[][5] const unsigned char x, const unsigned char y) works, but I don't want to hard code [5] into the code.

Any suggestions what to do to fix this?

gre_gor
  • 6,669
  • 9
  • 47
  • 52
Peter
  • 81
  • 1
  • 5
  • 2
    An array of arrays is *not* the same as a pointer to a pointer. See e.g. [this old answer of mine](https://stackoverflow.com/a/18440456/440558) for an explanation of why. – Some programmer dude Oct 15 '18 at 05:57
  • Thanks. Then my question is how do I pass an array of arrays without specifying the size explicitly? – Peter Oct 15 '18 at 06:01

1 Answers1

2

In C one solution is to use variable-length arrays, which can be done by switching the order of the arguments:

void foo (const unsigned char x, const unsigned char y, const unsigned char a[x][y]) { ... }

However this is problematic since Arduino is actually programmed using C++ and not C, and C++ doesn't have variable-length arrays (even though some compilers might have added it as an extension).

You can of course use the global constants (and array) directly instead of passing as arguments, unless you need to use the same function for different arrays of different sizes. Works with both C and C++. This with the caveat that global variables should be avoided as much as possible.

The natural C++ solution to your problem is to use std::vector, but I don't know how much of the C++ standard library is available, if any. You should probably study the Arduino documentation to see if there are other container types available for you.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621