gpt4 book ai didi

c - 我是 c 编程初学者,需要 sizeof() 字符串常量方面的帮助吗?

转载 作者:行者123 更新时间:2023-11-30 21:13:43 25 4
gpt4 key购买 nike

/**** Program to find the sizeof string literal ****/

#include<stdio.h>

int main(void)
{
printf("%d\n",sizeof("a"));
/***The string literal here consist of a character and null character,
so in memory the ascii values of both the characters (0 and 97) will be
stored respectively which are found to be in integer datatype each
occupying 4 bytes. why is the compiler returning me 2 bytes instead of 8 bytes?***/

return 0;
}

输出:

2

最佳答案

字符串文字"a" 的类型为char[2]。你可以想象它像下面的定义

char string_literal[] = { 'a', '\0' };

sizeof( char[2] ) 等于 2 因为(C 标准,6.5.3.4 sizeof 和alignof 运算符)

4 When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1.

C 中的字符常量确实具有 int 类型。例如 sizeof( 'a' ) 等于 sizeof( int ) 并且通常等于 4

但是当 char 类型的对象由这样的字符常量初始化时

char c = 'a';

应用隐式缩小转换。

关于c - 我是 c 编程初学者,需要 sizeof() 字符串常量方面的帮助吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45399393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com