从char *转换为带符号的char * [英] Conversion from char* to signed char*

查看:205
本文介绍了从char *转换为带符号的char *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了一段试图将其编译为C ++的有效C代码,但出现了我无法理解的错误。

I saw a piece of valid C code I tried to compile as C++ and I got an error I can't understand.

char* t;
signed char* v = t;




错误:来自 char *的无效转换/ code>到签名的字符*

从我学到的, char signed char 在语义上是相同的,但编译器仍认为它们是不同的。

From what I learned, char and signed char are semantically identical, but are still considered as different by the compiler.

我知道错误是由这两种类型之间的差异引起的,我的问题是:为什么存在这种差异?

I know that the error is caused by the difference between these two type, my question is: Why does this difference exists ?

据我所知, char 是作为签名的字符或作为未签名的字符,因此它应该彼此相同。

As far as I know char is implemented either as a signed char or as a unsigned char so it should be identical to either one or the other.

我咨询了这个问题,但没有回答问题我想知道。

I consulted this question and it doesn't answer the point I want to know.

推荐答案

实际上,我终于找到了规范部分在谈论这一点:

Actually I finally found the spec part talking about this:


3.9.1基本类型

3.9.1 Fundamental types


  1. 声明为字符(字符)的对象应为足以存储
    实现基本字符集的任何成员。如果该字符集中的字符
    存储在字符对象中,则该字符对象
    的整数值等于该字符的单字符
    文字形式的值。由实现定义的
    char对象是否可以包含负值。可以将
    字符明确声明为未签名或已签名。 普通字符,有符号字符和无符号
    字符是三种不同的类型。
    字符,有符号字符和无符号
    字符占用相同的存储空间并具有相同的存储空间对齐
    要求(3.11);也就是说,它们具有相同的对象
    表示形式。对于字符类型,对象
    表示形式的所有位都参与值表示形式。对于无符号
    字符类型,值表示形式
    的所有可能的位模式都表示数字。这些要求不适用于其他类型。在
    中的任何特定实现中,纯字符对象都可以采用与带符号字符或无符号字符相同的值。哪个是
    实现定义的。

  1. Objects declared as characters (char) shall be large enough to store any member of the implementation’s basic character set. If a character from this set is stored in a character object, the integral value of that character object is equal to the value of the single character literal form of that character. It is implementation-defined whether a char object can hold negative values. Characters can be explicitly declared unsigned or signed. Plain char, signed char, and unsigned char are three distinct types. A char, a signed char, and an unsigned char occupy the same amount of storage and have the same alignment requirements (3.11); that is, they have the same object representation. For character types, all bits of the object representation participate in the value representation. For unsigned character types, all possible bit patterns of the value representation represent numbers. These requirements do not hold for other types. In any particular implementation, a plain char object can take on either the same values as a signed char or an unsigned char; which one is implementation-defined.


这篇关于从char *转换为带符号的char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆