sizeof函数在函数中不起作用
sizeof Function not Working in Function
当我运行此代码时:
#include <iostream>
using namespace std;
void PrintLengthOfArray(double arr[])
{
int total_bytes = sizeof(arr);
int data_type_bytes = sizeof(arr[0]);
int length = total_bytes / data_type_bytes;
cout << "method 2: n";
cout << "total_bytes = " << total_bytes << "n";
cout << "data_type_bytes = " << data_type_bytes << "n";
cout << "length = " << length << "n";
}
int main()
{
double arr[3] = {1,2,3};
int total_bytes = sizeof(arr);
int data_type_bytes = sizeof(arr[0]);
int length = total_bytes / data_type_bytes;
// first method
cout << "method 1: n";
cout << "total_bytes = " << total_bytes << "n";
cout << "data_type_bytes = " << data_type_bytes << "n";
cout << "length = " << length << "nn";
// second method
PrintLengthOfArray(arr);
}
我得到:
method 1:
total_bytes = 24
data_type_bytes = 8
length = 3
method 2:
total_bytes = 8
data_type_bytes = 8
length = 1
也就是说,这就像函数中的total_bytes = sizeof(arr)
语句只计算单个元素的大小,或者只计算arr[0]
。怎么回事?
在第二个方法中,按值将数组传递给函数。它衰减为一个指针,因此大小是指针的大小,在您的情况下是8字节。请注意,函数声明
f(double arr[])
甚至
f(double arr[3])
由编译器翻译成
f(double*)
将数组传递给函数并保持其大小的唯一有意义的方法是通过引用传递,例如
void f(double (&arr)[3])
{
std::cout << sizeof arr << std::endl; // displays 3 * sizeof(double)
}
如果您希望能够传递任意长度的数组,我建议通过模板化函数进行引用传递:
template<typename T, size_t N>
void f(T (&arr)[N])
{
// N gives you the size in the body
}
如果您仍然希望按值传递,那么"检测"其大小的唯一方法就是向函数传递一个表示数组大小的附加参数。然而,这可能会引起很多头痛,而且很容易出错。使用std::vector
或std::array
可能会更好。
相关文章:
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- 为什么我的数组双精度函数不起作用?
- std::函数不起作用,但普通的旧函数指针可以 - 为什么?
- C++ Arduino - 随机函数不起作用
- 为什么我的数组或函数不起作用?
- 从类中的另一个文件请求函数不起作用
- 双链表堆栈删除函数不起作用
- 将 cmake 代码段转换为函数 - 不起作用
- 为什么我的从base64解码的函数不起作用?
- 为什么当我们使用等于'='符号比较器函数时,c ++的内置排序函数不起作用?
- swap(int&, int&) 函数不起作用,当交换不使用临时变量时?
- 子类化 STL 容器:范围构造函数不起作用
- 带有此指针的模板类多重继承构造函数不起作用?
- 以下打印树函数不起作用为什么?
- 为什么内存集函数不起作用?
- 调用填充我的主体数组的函数不起作用
- 带有自定义数字的阶乘函数不起作用
- 如何QDialog raise()函数不起作用
- Lambda 表达式闭包函数不起作用
- C++:在没有 lvalue 的情况下调用时复制构造函数不起作用