gpt4 book ai didi

c++ - C++ 编译器中的 C 代码

转载 作者:搜寻专家 更新时间:2023-10-31 00:03:36 25 4
gpt4 key购买 nike

我有以下代码,它是 tomcrypto 手册中的代码,不适用于 MS VC++ 2008 EE。有什么帮助吗?我还可以要求用 std::string 对象替换 char* 吗?

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

最佳答案

unsigned char *in = "hello world"

这在 C++ 中是不正确的:"hello world" 是一个字符串文字,类型为 const char[12]。在 C 中它是 char[12] 类型,但这里的 const 无关紧要,因为在 C++ 中有一个隐式(但已弃用)转换,允许字符串文字转换为 char*

问题是 charunsigned char 是不同的类型。 char 是否无符号并不重要;三种 char 类型(charunsigned charsigned char)都是不同的,在 C++ 中你不能无需转换即可在指向这三种类型的指针之间进行转换。

这在 C 中有效,因为在 C 中,您可以将任何指向对象的指针类型转换为任何其他指向对象的指针类型,而无需强制转换。在 C++ 中情况并非如此。

在 C++ 中,您需要使用:

// use the implicit conversion to 'char*' to cast away constness:
char* p = "hello world";

// explicitly cast to 'unsigned char*'
unsigned char* in = reinterpret_cast<unsigned char*>(p);

移除 constness 通常不是一个好主意,因为字符串文字是不可修改的,但有时在处理不是 const-correct 的遗留库时是必要的。

char*unsigned char* 的转换是安全的,因为所有的对象都可以被当作一个char 的数组, unsigned char,或 C++ 中的 signed char

关于c++ - C++ 编译器中的 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5717510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com