如何在C++中查找数组的大小

How to find the size of any array in C++

我想找到任何数组类型的大小。我的代码是:

#include <iostream>

using namespace std;

template <typename t>
int some_function(t arr []){
    int s;
    s = sizeof(arr)/sizeof(t);
    return s;
}

int main(){
    int arr1 [] = {0,1,2,3,4,5,6,7};
    char arr2 [] = {'a','b','c','d','e'};
    int size;
    size = some_function(arr1);
    cout << "Size of arr1 : "<<size<<endl;
    size = some_function(arr2);
    cout << "Size of arr2 : "<<size<<endl;
    return 0;
}

当我 运行 这段代码在 cpp.sh 输出是:

Size of arr1 : 2
Size of arr2 : 8

当我在 CodeBlocks 上 运行 并且 Visual Studio 输出是:

Size of arr1 : 1
Size of arr2 : 4

我希望它打印数组的确切大小,即:

Size of arr1 : 8
Size of arr2 : 5

解决方案

我在 rsp and Cheersandhth.-Alf. I was passing the array by value which is implicitly converted to pointer. After reading this article 的帮助下找到了解决方案,rsp 提供了答案,我通过引用传递了数组。所以最终代码是:

#include <iostream>

using namespace std;

template <typename t, int s>
int some_function(t (&arr)[s]){
    return s;
}

int main(){
    int arr1 [] = {0,1,2,3,4,5,6,7};
    char arr2 [] = {'a','b','c','d','e'};
    int size;
    size = some_function(arr1);
    cout << "Size of arr1 : "<<size<<endl;
    size = some_function(arr2);
    cout << "Size of arr2 : "<<size<<endl;
    return 0;
}

谢谢大家的帮助...

这叫做数组退化为指针。当您按值传递数组时,它们会衰减为指针。所以,数组的大小只不过是一个指针的大小,这取决于系统。

在调用函数时尝试添加数组的数据类型

size = some_function<int>(arr1);

size = some_function<char>(arr2);