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

时间:2017-11-04 09:57:49

标签: c++ arrays sizeof

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

#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

我在rspCheersandhth.-Alf的帮助下找到了解决方案。我通过值传递数组,该值被隐式转换为指针。阅读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;
}

谢谢大家的帮助......

2 个答案:

答案 0 :(得分:2)

它被称为衰变为指针的数组。按值传递数组时,它们会衰减为指针。因此,数组的大小只是指针的大小,取决于系统。

答案 1 :(得分:-4)

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

size = some_function<int>(arr1);

size = some_function<char>(arr2);