I'm trying to get an array of pointers to 2d arrays of booleans. How can this be achieved? This is for an Arduino (think they are a mix of C and C++?)
3 Answers
Based on your description, I think you're looking for something like:
bool (*arr[K])[M][N];
It breaks down as
arr -- arr
arr[K] -- is a K-element array
*arr[K] -- of pointers
(*arr[K])[M] -- to M-element arrays
(*arr[K])[M][N] -- of N-element arrays
bool (*arr[K])[M][N] -- of bool
2 Comments
bool is a different type from a 4x5 element array of bool, and a pointer to one isn't compatible with a pointer to the other.If you are using C++, and you don't want to input the size from the declaration, you can do that by allocating it dynamically.
int first_dim, second_dim;
// determine dimensions somewhere inside code
// create array of pointers to booleans
bool** arr[10];
for(i = 0; i < 10; i++){
arr[i] = new bool*[first_dim];
for(j = 0; j < first_dim; j++){
arr[i][j] = new bool[second_dim];
}
}
Make sure you delete all of your arrays when you are done using them.
NOTE
When you are trying to allocate 2d arrays, don't think of them as matrices or tables, each storing a boolean. For example, take an array of ints, an array declared as int arr[i][j], each element in the first "dimension" is of type int* and each element in the second "dimension" is of type int. So it is in fact an "array of arrays", if you will.
9 Comments
first_dim and second_dim to be known from the start? (see comments on answer by @JohnBode above)arr[n] as an 1-d arrays instead of a 2-d array and manually index arr[n][second_dim * i + j] (that's what I would do, if performance mattered)bool arr[i][j][k], bool[i] is bool (*)[k], not bool**...see thisT is convertible to T**, which is not the case; but anyway, they can read the comments so it's not a big deal.An array of pointers to 2D arrays of booleans looks like this (both in C and C++ - pick one, they're not the same language, nor a mixture):
typedef bool TwoDBoolArr[10][10];
typedef TwoDBoolArr *TwoDBoolArrPtr;
typedef TwoDBoolArrPtr TwoDBoolArrPtrArray[10];
You need the last typedef, of course.
If you want less typedefs and decreased readability:
typedef bool (*TwoDBoolArrPtrArray[10])[10][10];
Cthan inC++for dynamic allocation.