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

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

本文关键字:结果 元素 计算 数组 使用 sizeof      更新时间:2023-10-16

我正在编写一个简单的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 运行代码时,此消息没有显示,但我认为它可能会显示我的问题。

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

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

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

template <typename T>
void count(T a)

此外,我建议将sizeof(*a(替换为sizeof(a[0]( - 它是一样的,但更好地表达了它的含义。

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

这是因为您的template

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

衰减为:

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

因此,您打印sizeof指针,而不是像main那样打印数组。

错误消息如下:

将返回 int* 的大小