gpt4 book ai didi

c++ - unsigned long long是否固定为一个int(4字节)范围,如果是,为什么它在内存中是8字节?

转载 作者:行者123 更新时间:2023-11-28 07:38:50 24 4
gpt4 key购买 nike

编辑:愚蠢的问题,我忽略了格式标识符。

我有一个程序获取一些无符号类型的大小和它们的最大值。这引起了我的注意,即使认为 unsigned long long 是 8 个字节,它的范围似乎也固定为 4 个字节。 (char 是有保证的 8 位字节)

问题
我知道 unsigned long long 仅由标准定义为至少足以容纳 int (或者更确切地说 >= long int >= int 传递)。但是,如果它也限制在 4 个字节的范围内,为什么它使用 8 个字节的内存而不是与 int 相同的大小?

unsigned char:             255         1*sizeof(char)           
unsigned short: 65535 2*sizeof(char)
unsigned short int: 65535 2*sizeof(char)
unsigned int: 4294967295 4*sizeof(char)
unsigned long int: 4294967295 4*sizeof(char)
unsigned long long int: 4294967295 8*sizeof(char) //range[0..18446744073709551615]
unsigned long: 4294967295 4*sizeof(char)
unsigned long long: 4294967295 8*sizeof(char) //range[0..18446744073709551615]

这是我使用的来源:

#include <iostream>
#include <cstdio>

int main(void){

std::cout << "Type sizes: (multiples of char)"<< std::endl << "char: " << sizeof(char) << std::endl <<\
"short: " << sizeof() << std::endl <<\
"short int: " << sizeof(short int) << std::endl << std::endl <<\
"int: " << sizeof(int) << std::endl <<\
"long int: " << sizeof(long int) << std::endl <<\
"long long int: " << sizeof(long long int) << std::endl << std::endl <<\
"long: " << sizeof(long) << std::endl <<\
"long long: " << sizeof(long long) << std::endl << std::endl <<\
"float: " << sizeof(float) << std::endl <<\
"double: " << sizeof(double) << std::endl;

unsigned char c = -1;
unsigned short s1 = -1;
unsigned short int s2 = -1;

unsigned int i = -1;
unsigned long int i1 = -1;
unsigned long long int i2 = -1;

unsigned long l = -1;
unsigned long long l1 = -1;

printf("\
\nUnsigned Max: \n\
\nchar: %u\
\nshort: %u\
\nshort int: %u\
\nint: %u\
\nlong int: %u\
\nlong long int: %u\
\nlong: %u\
\nlong long: %u\
", c, s1, s2, i, i1, i2, l, l1);

return 0;
}

最佳答案

您为 printf 使用了错误的标志,这些值实际上没问题,但 printf 没有正确显示它们。为 unsigned long long 尝试 %llu

有关 printf(标志)的更多信息:http://www.cplusplus.com/reference/cstdio/printf/

关于c++ - unsigned long long是否固定为一个int(4字节)范围,如果是,为什么它在内存中是8字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16242386/

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