是否允许将字符 [] 转换为无符号字符 *
Is it allowed to cast a char[] to unsigned char *?
我正在使用一些类,它有一个需要的方法:
const unsigned char *sData
作为参数。
当我打电话给下面:
char dataIn[]="The quick brown fox jumps over the lazy dog";
obj.CRC(dataIn,strlen(dataIn),&checksum); // compute checksum
我收到错误:
Error 1 error C2664: 'void crcClass::CRC(const unsigned char *,size_t,unsigned int *)' : cannot convert parameter 1 from 'char [44]' to 'const unsigned char *'
所以我像这样修改了上面的代码,它可以工作:
obj.CRC((const unsigned char*)dataIn,strlen(dataIn),&checksum); // compute checksum
我所做的修改正常吗?
没
关系,但为了"安全",请考虑改用reinterpret_cast<const unsigned char*>(dataIn)
。
这更安全,因为reinterpret_cast
不能去除const
或volatile
,而C型铸件可以。如果您不想删除限定符,那么当您出错时代码无法编译是件好事。
当然,在这种情况下,出错的可能性很小 - 目的地是const
合格的,你可能会注意到源是否volatile
合格。但是养成让编译器帮助你的习惯仍然很有用,而且有些人会认为代码更容易阅读。
如果可能的话,为普通char
添加一个重载,并将强制转换隐藏在CRC类中:
class crc32 {
// ...
unsigned int CRC(unsigned char const *in) {
// existing function
}
unsigned int CRC(char const *in) {
// pass through to preceding function:
return CRC(reinterpret_cast<unsigned char const *>(in);
}
};
我还要注意到,乍一看crc32::CRC
对我来说很可疑。看起来将其写为operator()
的重载可能更有意义。
相关文章:
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 尝试将字符串/字符转换为整数会产生意外结果
- 如何使用C++将字符串中的字符转换为整数变量
- 字符转换功能 std::isupper() & std::islower() C++17
- 将字符 * 转换为字符串 *
- 在编译时将常量字符* 转换为常量 char_type*
- 如何在 C/C++ 中将无符号字符*转换为无符号字符数组?
- 错误:请求从"常量字符 [5]"转换为非标量类型"字符串"
- 无法使用字符串流将字符转换为字符串C++
- 将无符号字符 C++ 转换为 C#
- C++:使用没有位移位的指针将无符号字符转换为无符号 int
- 为什么我可以隐式地将字符*转换为常量字符*,但不能将无符号字符*
- 无法<string>从"常量字符 []"转换为<类名>
- 不能将字符转换为整数吗?
- 编译时将字符*转换为字节
- CP1251:从字符* 转换为 wchar_t* 时的编码失真
- 将单个字符转换为 std::string 前缀 \x01
- PPM 将字符转换为 int 授予负数
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类
- 将常量字符* 转换为字符时出错