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
}
  • 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`. – sweenish Jan 04 '22 at 21:24
  • @Immanuel Charles Declare the parameter as having a referenced type. That is pass the array by reference. – Vlad from Moscow Jan 04 '22 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. – Eljay Jan 04 '22 at 21:28
  • Outside of this function. How is your array declared and how would you determine its length? – John Jan 04 '22 at 21:32
  • @sweensih thanks for the suggestion but I dont know the size of the array and std::array needs the size – Immanuel Charles Jan 04 '22 at 21:36
  • @John I declare the array without the size. I determen its length by using this line of code: `sizeof(arr) / sizeof(arr[0]);` – Immanuel Charles Jan 04 '22 at 21:37
  • You could use std::array or std::vector instead of an C array altogether or create a std::range parameter from your C array – Sebastian Jan 04 '22 at 21:39
  • Maybe post some code for context. – Joseph Larson Jan 04 '22 at 21:40
  • Use your calculation to pass the size to the function. As of C++17, `std::array arr{1, 2, 3};` compiles just fine. – sweenish Jan 04 '22 at 21:46
  • 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 – Sebastian Jan 04 '22 at 22:01

1 Answers1

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.
}
Martin York
  • 257,169
  • 86
  • 333
  • 562