sizeof(' ') null terminator as literal 是四个字节,但是为什么在字符串中它只需要一个字节?

问题描述 投票:0回答:1

在 c ' ' 中,null-terminator as literal 需要 4 个字节(因为它在内部只是零)但是为什么它在字符数组或字符串中使用时只需要 1 个字节?这个编译器是不是很神奇?

程序员在使用动态内存分配来处理空终止符大小时是否需要特别小心?下面的程序可以吗?

#include<stdio.h>
#include<stdlib.h>

int main()
{
   printf("size of null-termination: %lu\n", sizeof('\0')); //outputs 4 bytes
   printf("size of 0: %lu\n", sizeof(0)); // outputs 4 bytes

   char *message = malloc(10);
   message[0] = 'A';
   message[1] = 'B';
   message[2] = 'C';
   message[3] = '\0'; // takes 1-byte in below memory layout(attached image)

   message[4] = 'a';
   message[5] = 'b';
   message[6] = 'c';
   message[7] = '\0'; // takes 1-byte in below memory layout(attached image)

   message[8] = 'X';
   message[9] = 'Y';

   printf("\n");
   return 0;
}

c malloc c-strings sizeof null-terminated
1个回答
5
投票

在与 C++ 相对的 C 中,

'\0'
是一个整型字符常量,类型为
int
.

在字符串文字中,这样的转义序列存储为一个字符。

来自 C 标准(6.4.4.4 字符常量)

10 整型字符常量的类型为 int。整数的值 包含单个字符的字符常量映射到 单字节执行字符是数值 映射字符的表示解释为整数

和(6.4.5 字符串文字)

6 在翻译阶段 7,一个字节或值为零的代码被附加到 由字符串文字产生的每个多字节字符序列 或文字。78)多字节字符序列然后用于 初始化一个静态存储持续时间和长度的数组 足以包含序列。 对于字符串文字, 数组元素的类型为 char,并使用 多字节字符序列的各个字节.

© www.soinside.com 2019 - 2024. All rights reserved.