有没有办法将数组指针转换回常规数组



我试图通过函数传递数组,但当我试图获得数组的长度时,它会给出指针的长度。有没有办法将数组指针转换回常规数组?

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
}

您可以将参数声明为对数组的引用。

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

为了避免必须知道尺寸,你可以在尺寸上使用模板

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.
}

最新更新