c++:创建返回数组大小的函数



我想在c++中创建一个函数,使用指针返回任何数组的大小:*(&array + 1) - array。这样的:

#include <iostream>
using namespace std;
void arrayLength(string array[]) {
int arraySize = *(&array + 1) - array;

cout << "Size of the array: " << arraySize << endl;
}
int main ()
{
string myArray[] = {"a", "b", "c", "d"};
arrayLength(myArray);
//  Output: It seems to return the size in bytes (different numbers like this: 381286345)
return 0;
}

And this Code works:

#include <iostream>
using namespace std;
int main () {
string array[] = {"a", "b", "c", "d"};
cout << *(&array + 1) - array << endl;

return 0;
}

很好的说明了为什么普通的原始数组是危险的。

问题是指针算术和+1。对于T* ptr;,ptr+1指针前进sizeof(T)字节,或前进一个T

在main中,&array的类型是string(*)[4],所以指针加sizeof(string)*4。这将导致正确的大小。

相反,即使使用[],arrayLength()中的string array[]也具有string*类型。增量只有sizeof(string*)字节,因此会导致不正确的大小。

只使用std::arraystd::vector与他们的size()

我同意另一个答案,如果可能的话,您应该使用std::arraystd::vector。但是,如果不允许使用STL或者有其他好的理由使用纯C数组,那么有一个可能的模板解决方案:

template<class T, size_t N>
size_t getArrayLength(T(&arr)[N])
{
return N;
}

用任意数组作为参数调用这个模板。请注意,用指针调用this是行不通的,但至少你会得到一个编译器错误,而不是奇怪的运行时行为。

最新更新