是否允许将字符 [] 转换为无符号字符 *

Is it allowed to cast a char[] to unsigned char *?

本文关键字:字符 转换 无符号 是否      更新时间:2023-10-16

我正在使用一些类,它有一个需要的方法:

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不能去除constvolatile,而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()的重载可能更有意义。