0

When passing an array to a function, you usually pass the length of the array along with it. You can compute the size of the array with sizeof(myArray)/sizeof(myArray[0]), which works just fine.

However, if you try to do this within the function that you pass the array to, this doesn't return the length of the array - eg. if it is an int array, it returns 1, if it is a double array, it returns 0.

Why is that so and is there any way to compute the size of an array that was passed as a parameter?

1
  • If you don't use it often (every different type/size makes new instantiation od f function), then you can use templates like: template <typename T, size_t N> void f(T(& myArray)[N])
    – KIIV
    Commented Nov 12, 2019 at 11:44

1 Answer 1

2

You can't. You are passing a pointer to the array, and sizeof will give you the size of that pointer (2 on an 8-bit Arduino).

Instead the normal way is to pass the size of the array as a parameter to your function.

myFunction(myArray, sizeof(myArray) / sizeof(myArray[0]));
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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