C++ 无法从 'unsigned char *' 转换为 'char *'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12351554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
cannot convert from 'unsigned char *' to 'char *'
提问by Hashed
Possible Duplicate:
C++ style cast from unsigned char * to const char *
I have the unsigned char* digest;
which is the output of a program and i would like to pass it to a char* S1;
我有unsigned char* digest;
一个程序的输出,我想将它传递给char* S1;
I type char* S1=digest;
and does not work
我打字char* S1=digest;
但不工作
回答by perh
The simple answer: You need to cast it: reinterpret_cast<unsigned char*>(digest)
简单的答案:您需要投射它: reinterpret_cast<unsigned char*>(digest)
However, in this case you need to be aware that unsigned char* and char* are not really the same thing unless all elements in the array are less than 128.
但是,在这种情况下,您需要注意 unsigned char* 和 char* 并不是真正相同的东西,除非数组中的所有元素都小于 128。
char * either represents values from -128 to 127 (signed) or 0 to 255 (unsigned), the other always values from 0 to 255.
char * 表示从 -128 到 127(有符号)或 0 到 255(无符号)的值,另一个总是从 0 到 255 的值。
digest functions by their nature are likely to return values between 0 and 255, inclusive, in the result.
摘要函数的性质很可能在结果中返回 0 到 255 之间的值,包括 0 和 255。
Also, the fact that the array might very well include null characters (the question does not really specify where the digest is coming from) many functions that accept char * or unsigned char* are likely to fail, since they assume the char* is a string (which it is not, really, if it is a binary digest of (presumably) fixed size)
此外,数组很可能包含空字符这一事实(问题并没有真正指定摘要的来源)许多接受 char * 或 unsigned char* 的函数可能会失败,因为它们假设 char* 是一个字符串(实际上,如果它是(大概)固定大小的二进制摘要,则它不是)
回答by Some programmer dude
It's because unsigned char
and char
(which is really signed char
in your compiler) are different. You have to make an explicit typecast:
这是因为unsigned char
和char
(实际上signed char
在您的编译器中)是不同的。您必须进行显式类型转换:
char* S1 = reinterpret_cast<char*>(digest);
回答by Kerrek SB
Char types are layout compatible, so if you know what you're doing, you can simply force the pointer with a reinterpreting cast:
Char 类型是布局兼容的,所以如果你知道你在做什么,你可以简单地通过重新解释强制转换来强制指针:
char * s1 = reinterpret_cast<char *>(digest);
回答by Software_Designer
C style cast: s1=( char *)digest;
C风格演员表: s1=( char *)digest;
C++ style cast: s1= reinterpret_cast<char *>(digest);
C++ 风格转换: s1= reinterpret_cast<char *>(digest);
#include <iostream>
using namespace std ;
int main(void)
{
unsigned char* digest;
char * s1c,*s1cpp;
//C style cast
s1c=( char *)digest;
//C++ style cast
s1cpp= reinterpret_cast<char *>(digest);
cout<<" \nPress any key to continue\n";
cin.ignore();
cin.get();
return 0;
}