【问题标题】:C sizeof char pointerC sizeof char 指针
【发布时间】:2012-12-27 01:18:00
【问题描述】:

为什么这个 char 变量的大小等于 1?

int main(){

char s1[] = "hello";

fprintf(stderr, "(*s1) : %i\n", sizeof(*s1) )    // prints out 1

}

【问题讨论】:

  • sizeof(char) = 1, * 是地址运算符的值。 *s 只不过是第一个字符。这就是你的情况h。所以sizeof(*s)=1,有趣的是sizeof(s1) 是6
  • @GrijeshChauhan ASCII 有 128 代码而不是 256
  • @KerrekSB 你知道扩展 ASCII 图表吗?它最多 256 即 0 到 255...
  • 我认为 C 不知道扩展的 ASCII 图表。
  • 运算符sizeof 产生size_t 类型的值。即使忽略您在范围内没有原型的情况下调用“可变参数”函数这一事实,使用 "%i" 而没有相应的 int 参数也是错误的。使用"%zu" 或强制转换值。哦!并包含正确的标题。

标签: c pointers char sizeof


【解决方案1】:

注意:最初的问题有一点变化:为什么这个 char 指针的大小是 1

sizeof(*s1)

一样

sizeof(s1[0])char 对象的大小,而不是 char 指针的大小。

char 类型对象的大小在 C 中始终为 1

要获取char 指针的大小,请使用以下表达式:sizeof (&s1[0])

【讨论】:

    【解决方案2】:

    为什么这个 char 变量的大小等于 1?

    因为 C 标准保证 char 的大小为 1 字节。

    *s1 == *(s1+0) == s1[0] == char
    

    如果要获取字符指针的大小,需要将字符指针传递给sizeof

    sizeof(&s1[0]);
    

    【讨论】:

      【解决方案3】:

      因为您要延迟从数组s1 衰减的指针,所以您获得了第一个指向元素的值,即charsizeof(char) == 1

      【讨论】:

        【解决方案4】:

        sizeof(*s1) 表示“s1 指向的元素的大小”。现在s1chars 的数组,当被视为指针时(它“衰减”为指针),取消引用它会产生char 类型的值。

        而且,sizeof(char)始终是一。 C 标准要求它是这样的。

        如果您想要整个数组的大小,请改用sizeof(s1)

        【讨论】:

        • sizeof(s1) 返回大小,包括\0,我认为他不想要它。
        • @Jack 是的,确实如此。谁在乎?应该知道strlen()
        【解决方案5】:
        sizeof(*s1) means its denotes the size of data types which used. In C there are 1 byte used by character data type that means sizeof(*s1) it directly noticing to the character which consumed only 1 byte.
        
        If there are any other data type used then the **sizeof(*data type)** will be changed according to type.
        

        【讨论】:

          猜你喜欢
          • 2019-07-20
          • 2021-11-26
          • 2021-01-26
          • 2010-12-24
          • 1970-01-01
          • 2017-09-04
          • 1970-01-01
          • 2012-03-19
          相关资源
          最近更新 更多