什么时候在C中无符号和有符号字符指针之间的转换变得不安全? [英] When does conversion between unsigned and signed character pointer becomes unsafe in C?
问题描述
如果我在 clang
和 Visual Studio
中都这样做:
If I do this in both clang
and Visual Studio
:
unsigned char *a = 0;
char * b = 0;
char x = '3';
a = & x;
b = (unsigned char*) a;
我得到警告,我正在尝试在有符号和无符号字符指针之间进行转换,但是代码确实有效。尽管编译器之所以这样说是有原因的。您能指出可能会变成问题的情况吗?
I get the warning that I am trying to convert between signed and unsigned character pointer but the code sure works. Though compiler is saying it for a reason. Can you point out a situation where this can turn into a problem?
推荐答案
为了简单起见,因为 char
表示:
To make it very simple because char
represents:
- 单个字符(
char
,无论是否签名都没有关系。当您分配诸如'A'
之类的字符时,您要做的是在该内存位置中写入 A ASCII码(65)。 - 一个字符串(当用作
char
缓冲区的数组或指针时)。 - 八个数字(带或不带符号)。
- A single character (
char
, it doesn't matter if signed or not). When you assign a character like'A'
what you're doing is to write A ASCII code (65) in that memory location. - A string (when used as array or pointer to a
char
buffer). - An eight bit number (with or without sign).
然后,当您将诸如-1的带符号字节转换为无符号字节会丢失信息(至少有符号但也可能有数字),这就是为什么您会收到警告:
Then when you convert a signed byte like -1 to unsigned byte you'll loose information (at least sign but probably number too), that's why you get a warning:
signed char a = -1;
unsigned char b = (unsigned char)a;
if ((int)b == -1)
; // No! Now b is 255!
值可能不是255>,但如果系统不代表则为1具有2的补数的负数,在该示例中,它并不重要(我从未使用过类似的系统,但它们确实存在),因为概念是有符号/无符号转换可能会丢弃信息。不管是由于显式强制转换还是通过指针强制转换而发生,这都没有关系:位将表示其他内容(结果将根据实现,环境和实际值而改变)。
Value may not be 255 but 1 if your system doesn't represent negative numbers with 2's complement, in that example it doesn't really matter (and I never worked with any system like that but they exist) because the concept is a signed/unsigned conversion may discard information. It doesn't matter if this happens because of an explicit cast or a cast through pointers: bits will represent something else (and result will change according to implementation, environment and actual value).
请注意,对于C标准 char
,带符号的字符
和无符号的字符
是形式上不同的类型。您将不会在乎(VS会将 char
默认为 signed
或 unsigned
,但这不是可移植的),您可能需要强制转换。
Note that for C standard char
, signed char
and unsigned char
are formally distinct types. You won't care (and VS will default char
to signed
or unsigned
according to a compiler option but this isn't portable) and you may need casting.
这篇关于什么时候在C中无符号和有符号字符指针之间的转换变得不安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!