使用 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 运行代码时,此消息没有显示,但我认为它可能会显示我的问题。
这两个不同的结果从何而来?
我无法精确预测编译器如何解释您的代码,但是您认为您调用的模板函数中的 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* 的大小
相关文章:
- C++:使用类在向量中搜索特定元素时,我得到了错误的结果
- AVX2 整数乘以有符号 8 位元素,产生有符号 16 位结果?
- 如何通过查找迭代器结果分配给一组对的元素
- 使用指针访问数组元素时出现意外结果
- 我写了这个简单的代码,应该计算一系列数组元素的最高数量,但结果很奇怪
- 打印整数指针元素时的结果不同
- 使用算法中的插入函数将元素插入空容器中,未给出预期的结果
- 从函数的返回值将元素C++存储到 std::vector 中时出现意外结果
- 第一个字符串元素的地址产生意外结果
- 求和数组的每个元素的函数的结果
- 将多态函数应用于每个元组元素的结果类型
- 试图将字符串的两个元素组合在一起会得到错误的结果(c++)
- 为什么我的程序是,数组中任意两个元素之间的最小差异,给出相反的结果
- 如何将函数静态应用于非类型模板包的各个元素并对结果求和
- 如何进行每个元素的比较,并根据结果进行不同的操作
- 在条件与外部获取数组元素的结果不同
- unordered_multimap-迭代find()的结果会产生具有不同值的元素
- 在哪里存储Visitor模式中访问的每个元素的计算结果
- 是否有可能判断哪个数组元素比较结果为真?
- 如何使用本函数对两个字符数组进行元素相乘,并将相乘结果求和为int