提问者:小点点

字符数组转换为无符号字符*


所以我有一个接收指针的函数:

int myfunc( const char *token, unsigned char *plaintext )

我做了我工作,最后得到了一个char数组:

unsigned char my_plaintext[1024];

现在我需要将指针(plaintext)设置为my_plaintext中的内容。 我试过很多不同的方法,但我还没弄明白这一条。

这部分在一个cpp文件中,我甚至尝试过:

std::string tmpstr( my_plaintext );

但这又是:

token_crypto.cpp:131:13: error: invalid conversion from 'char*' to 'unsigned char*' [-fpermissive]
         my_plaintext
         ^~~~~~~~~~~~

std::string tmpstr( (char *)my_plaintext );

'�5�B'

这做编译但内容全错了:

谢谢大家!


共2个答案

匿名用户

如果您知道plaintext已经指向1024长(或更长)的数组,则可以使用memmove():

int myfunc( const char *token, unsigned char *plaintext )
{
    unsigned char my_plaintext[1024];
    /* ... fill in my_plaintext here ... */
    memmove(plaintext, my_plaintext, 1024);
    /* ... rest of function ... */
}

请注意,memmove的参数是destintation,然后是source,而不是反过来。

由函数的调用者来确保他们传递的指针至少指向1024字节。

在这种情况下,您可以改用memcpy(),但通常使用memmove()是很好的实践。

匿名用户

C++字符串构造函数不接受无符号字符*。 请参阅此处的C++参考:

http://www.cplusplus.com/reference/string/string/string/

需要将无符号char数组强制转换为char数组。 请在此处查看如何执行此操作:

在C++中如何将无符号Char*转换为Std::String?