I have written a function that takes in a dynamic length array but with fixed inner array size, the second parameter in the function is the length of the parent array. When I try to access the nested values however, I get the issue mentioned above.
void myFunc(int arrOfArr, int arrOfArrLen) {
// try to access
arrOfArr[0][1]; // expect val2
}
example usage
myFunc(
{
{val1, val2},
{val3, val4}
},
2
);
edit: I realize "contextually" obviously an integer has no indexes, but that's how you declare an array it seems...(truthfully in Arduino context) but apparently it's still C++
Here's a runable demo of above from the first sandbox Google returned
update
I did find a solution, it's ugly but it works:
instead of passing in a "raw" nested array as a param, I set it as a variable first eg:
int arrOfArr[][3] = {
{val1, val2},
{val3, val4}
}
Then in the function I do the same thing
void myFunc(int arrOfArr[][3], int arrOfLen) {
// access
}
Call it
myFunc(arrOfArr, 2);
As I said it's ugly but works for me, this is a passing project thing not a low-level dev, maybe will learn it fully later on but not needed in day job.
edit: apparently the thing I was trying to do initially eg. embed an initializer list as a param does not work.
if you want to pass a nested array, the declaration may be:
template<size_t N>
void myFunc(int const arrOfArr[][N], int arrOfArrLen) {
// ...
}
and you can remove the template argument if N
is already decided.
const size_t N = 3;
void myFunc(int const arrOfArr[][N], int arrOfArrLen) {
// ...
}
but it doesn't work if you pass a brace-enclosed initializer, you can add a overloaded function:
template<size_t M, size_t N>
void myFunc(int const (&arrOfArr)[M][N], int arrOfArrLen){
// attention: int *const*
// ...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.