1

I am trying to pass an array through a function but when I try to get the length of the array it gives me the length of the pointer. Is there any way to convert the array pointer back into a regular array?

float arr[] = {10, 9, 8]

void func(float arr[])
{
   // now I want to figure out the size of the array 
   int lenArr = sizeof(arr) / sizeof(arr[0]); // this will get the size of the pointer to the array and not the actual array's size
}
10
  • 6
    With C-style arrays, always pass the size along with the array, which will decay to a pointer. Or scrap that type and use std::array. Commented Jan 4, 2022 at 21:24
  • @Immanuel Charles Declare the parameter as having a referenced type. That is pass the array by reference. Commented Jan 4, 2022 at 21:26
  • If you must pass in a C-style array (which will be a pointer to the first element of the array), also pass in the std::size_t size of the number of elements in the array. Commented Jan 4, 2022 at 21:28
  • Outside of this function. How is your array declared and how would you determine its length? Commented Jan 4, 2022 at 21:32
  • 2
    The size calculation only works before passing the array into a function as parameter (that is why some commenters suggested an additional size parameter). Using C arrays is in general not recommended for C++. Especially because of those limitations, which could lead to errors or security issues, if the function accesses the array behind the end. Try std::vector<float> Commented Jan 4, 2022 at 22:01

1 Answer 1

4

You can declare the parameter a reference to an array.

void func(float (&arr)[10])
{
    // but you have to know the size of the array.
}

To get around having to know the size, you can template on size

template<int Size>
void func(float (&arr)[Size])
{
    // Now the size of the array is in "Size"
    // So you don't need to calcualte it.
}
Sign up to request clarification or add additional context in comments.

2 Comments

One should mention that the size has to be determined/-able at compile time even with the template solution
@Sebastian True. But also true for the C style array being passed in the OP question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.