C ++编译器中的C代码
|
我有以下代码,它是tomcrypto手册中的代码,在MS VC ++ 2008 EE上不起作用。有什么帮助吗?我也可以要求将“ 0”替换为“ 1”对象吗?
int main(void)
{
hash_state md;
unsigned char *in = \"hello world\", out[16];
/* setup the hash */
md5_init(&md);
/* add the message */
md5_process(&md, in, strlen(in));
/* get the hash in out[0..15] */
md5_done(&md, out);
return 0;
}
错误:
\\main.cpp(7) : error C2440: \'initializing\' : cannot convert from \'const char [12]\' to \'unsigned char *\'
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
.\\main.cpp(11) : error C2664: \'strlen\' : cannot convert parameter 1 from \'unsigned char *\' to \'const char *\'
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
编辑:现在代码看起来像:
int main(void)
{
register_hash(&md5_desc);
hash_state md;
char* p = \"hello wordl\";
unsigned char *in = reinterpret_cast<unsigned char*>(p);
char* out[16];
/* setup the hash */
md5_init(&md);
/* add the message */
md5_process(&md, const_cast<char*>(in), strlen(in));
/* get the hash in out[0..15] */
md5_done(&md, out);
return 0;
}
错误:
\\main.cpp(21) : error C2440: \'const_cast\' : cannot convert from \'unsigned char *\' to \'char *\'
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
.\\main.cpp(21) : error C2664: \'strlen\' : cannot convert parameter 1 from \'unsigned char *\' to \'const char *\'
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
.\\main.cpp(23) : error C2664: \'md5_done\' : cannot convert parameter 2 from \'char *[16]\' to \'unsigned char *\'
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
没有找到相关结果
已邀请:
4 个回复
撕吠
这在C ++中是不正确的:
是字符串文字,类型为
。在C语言中,其类型为
,但此处的
并不重要,因为在C ++中存在隐式(但已弃用)转换,该转换允许将字符串文字转换为
。 问题在于
和
是不同的类型。 ѭ12是否为无符号无关紧要;三种
类型(
,
和
)都是截然不同的,在C ++中,如果没有强制转换,就无法在指向这三种类型的指针之间进行转换。 这在C语言中有效,因为在C语言中,您无需转换即可将任何指针到对象的类型转换为任何其他指针到对象的类型。在C ++中不是这种情况。 在C ++中,您需要使用:
删除常量性通常不是一个好主意,因为字符串文字不可修改,但是有时在处理不符合const正确性的旧版库时有时是必要的。 从
到
的转换是安全的,因为在C ++中所有对象都可以视为
,
或
的数组。
纤洞需匪
是与
或
不同的类型;字符串文字始终为
类型;因此您不能将它们指定为
或
。要解决此问题,请从第4行中删除
。 如果您的
函数显式接受
作为参数,那么您应该在此时进行强制转换:
[正如其他人所说的,您应该将
定义为
,因为它指向字符串文字,但这不是问题。]
擅香
这样行吗?
嘘崇蔡对
但是,如果md5_process接受非常量
,则可能会导致问题,在这种情况下,您将不得不强制转换为非常量: