简体   繁体   English

将'char *'转换为'signed char *'

[英]cast 'char *' to 'signed char *'

Is there any danger in casting a char * type to signed char * in C, where the char array is interpreted as a byte array. 在C中将char *类型转换为signed char *是否存在任何危险,其中char数组被解释为字节数组。

I've read that in gcc, the char type can be either unsigned or signed depending on the system. 我在gcc中读过, char类型可以是无符号的,也可以是签名的,具体取决于系统。 In the 'worst' case, the char * would be a unsigned char * , but as the array is just interpreted as a series of bits, it doesn't matter if the type goes from unsigned to signed. 在'最坏'的情况下, char *将是一个unsigned char * ,但由于该数组只被解释为一系列位,因此类型从无符号到有符号无关紧要。

(BTW, I've checked other posting, but I've only seen the question re: casting unsigned char to signed char , and I wondering if there's anything unique to just plain char . Thanks in advance.) (顺便说一句,我已经检查了其他帖子,但我只看到了问题:将unsigned charsigned char ,我想知道是否有任何特殊的纯粹char 。请提前感谢。)

There shouldn't be any problem in the cast itself, especially if you are just interpreting the array as bytes. 转换本身应该没有任何问题,特别是如果你只是将数组解释为字节。 In this case though I would suggest that you consider using the C99 types uint8_t and int8_t to convey your intentions better, if they are available to you. 在这种情况下,虽然我建议您考虑使用C99类型uint8_tint8_t来更好地传达您的意图,如果它们可供您使用。

没有危险,它明确允许在所有三种char类型中重新解释char指针,并且还将任何对象指针重新解释为char指针(因此将任何对象视为字节数组)。

there are some edge cases with comparisons after the assignment, but for storage and handing to different functions, no there isn't any danger... 在分配后有一些边缘情况进行比较,但是对于存储和处理不同的功能,没有任何危险......

also in your implementation char may be signed or unsigned by default... 在您的实现中,默认情况下char可能是签名或未签名的...

example of a problem with comparison and signedness: 比较和签名问题的示例:

on MacOS X with clang in c99 在MacOS X上使用c99中的clang

char * dog = malloc(1);
dog[0]= 0xff;
unsigned char * mansBestFriend = dog;

if (mansBestFriend[0] > dog[0]) {
    puts("boy that is strange");
}

outputs: boy that is strange 输出:奇怪的男孩

because of the sometimes confusing comparison rules in C, the comparison happens in a way that may seem strange. 由于C中有时令人困惑的比较规则,比较的方式可能看起来很奇怪。

There are a lot of other times when this can happen, and the ones that I can never remember are the cases where one of the values is larger than the other and one is signed and the other is not... it is better to cast to be explicit if you are doing comparisons of disparate types. 还有很多其他时候会发生这种情况,而我永远无法记住的是其中一个值比另一个大,一个是签名而另一个不是......的情况。如果您正在对不同类型进行比较,那么要明确。

不,这样做没有危险,因为您只想将其用作字节值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM