如何将 int 指针转换为 float 指针
How to cast int pointer to float pointer
我 运行 cppcheck (c++11) 针对包含许多类似于以下强制转换的库:
// Allocates various buffers
int* i_buffer = (int*) calloc (500, sizeof (int));
float* f_buffer = (float*) i_buffer;
对于这些转换,我看到以下消息:
"portability","invalidPointerCast","Casting between integer* and float* which have an incompatible binary data representation."
执行上述类型转换的正确方法是什么?按照上面显示的方式投射指针的潜在后果是什么?
How to cast int pointer to float pointer
使用重新解释转换。
但是不要尝试那样做,因为重新解释的指针不会有用。
What is the correct way to perform the type of cast shown above ?
显示的演员表本身已经很好地定义了;做这样的转换是没有用的。
如果你需要分配一个浮点数数组,你可以使用下面的代替:
std::vector<float>(500);
通过 new(这是 C++ 标准)使用旧式 C 数组也是合法的:
float* f_buffer = new float[500];
注意将该内存的释放调整为:
delete [] f_buffer;
应始终避免类型转换,以保持代码干净并允许编译器验证代码的正确性。
严格来说,由于违反了严格别名,您的代码行为未定义。
实际上,如果 int
和 float
大小相同(它们在许多桌面平台上都有,尽管有一些推动将 int
移动到 64 位),那么代码将 运行 没有错误。虽然再重申一遍,从标准C++的角度来看,绝对不能保证这一点。
但你还是应该修复它。直接分配 float
数组是明智的做法:
float* f_buffer = (float*) calloc (500, sizeof (float));
我 运行 cppcheck (c++11) 针对包含许多类似于以下强制转换的库:
// Allocates various buffers
int* i_buffer = (int*) calloc (500, sizeof (int));
float* f_buffer = (float*) i_buffer;
对于这些转换,我看到以下消息:
"portability","invalidPointerCast","Casting between integer* and float* which have an incompatible binary data representation."
执行上述类型转换的正确方法是什么?按照上面显示的方式投射指针的潜在后果是什么?
How to cast int pointer to float pointer
使用重新解释转换。
但是不要尝试那样做,因为重新解释的指针不会有用。
What is the correct way to perform the type of cast shown above ?
显示的演员表本身已经很好地定义了;做这样的转换是没有用的。
如果你需要分配一个浮点数数组,你可以使用下面的代替:
std::vector<float>(500);
通过 new(这是 C++ 标准)使用旧式 C 数组也是合法的:
float* f_buffer = new float[500];
注意将该内存的释放调整为:
delete [] f_buffer;
应始终避免类型转换,以保持代码干净并允许编译器验证代码的正确性。
严格来说,由于违反了严格别名,您的代码行为未定义。
实际上,如果 int
和 float
大小相同(它们在许多桌面平台上都有,尽管有一些推动将 int
移动到 64 位),那么代码将 运行 没有错误。虽然再重申一遍,从标准C++的角度来看,绝对不能保证这一点。
但你还是应该修复它。直接分配 float
数组是明智的做法:
float* f_buffer = (float*) calloc (500, sizeof (float));