使用 sizeof 计算数组中元素数时的不同结果

Different results when using sizeof to count number of elements in array

我正在编写一个简单的 C++ 代码来计算数组中元素的数量。我使用模板,以便我可以处理不同类型的数组。

template <typename T>
void count(T a[]){

    cout << "size of array: " << sizeof(a) << endl;
    cout << "size of element: " << sizeof(*a) << endl;
    cout << "count number: " << sizeof(a)/sizeof(*a) << endl;
}

int main()
{
    int x[6] ={1,2,3,4};

    count(x);
    cout << sizeof(x) << endl;
    cout << sizeof(*x) << endl;
    cout << sizeof(x)/sizeof(*x) << endl;

    return 0;
}

但是当我 运行 这段代码时,我通过使用函数 count 和仅在 main 中复制相同的代码得到了不同的结果。我不知道为什么。 结果是这样的:

size of array: 8
size of element: 4
count number: 2
24
4
6

更重要的是,当我使用g++编译器运行代码时,出现警告信息:

warning:sizeof on array function parameter 'a' will return size of int* [-Wsizeof-array-argument]
  cout << "size of array: " << sizeof(a) << endl;

当我使用 Code::Blocks 运行 代码时,这条消息没有出现,但我认为它可能显示了我的问题。

这两个不同的结果从何而来?

因为你的template:

template <typename T>
void count(T a[])

衰减为:

template <typename T>
void count(T a*)

所以你正在打印 sizeof 一个指针,而不是像你的 main 那样的数组。

错误消息是这样说的:

will return size of int*

我无法准确预测编译器如何解释您的代码,但您认为您调用的模板函数中的 T 是什么?诠释?或 int[]?或 int[6]?或者更确切地说 int[4] (初始化大小)?

您必须将完整的数组定义为模板类型 T,因此正确的声明应该是:

template <typename T>
void count(T a)

我还建议用 sizeof(a[0]) 替换 sizeof(*a) - 它是一样的,但表达的意思更好。

顺便说一句。有一个标准宏 _countof,它为您提供数组元素的数量。