C编程-2U和1024U的大小

C Programming - Size of 2U and 1024U

我知道U字面量在c中的意思是,该值是一个无符号整数。无符号整数大小为 4 个字节。

但是2U或1024U有多大?例如,这只是意味着 2 * 4 字节 = 8 字节,还是表示 2(或 1024)是无符号整数?

我的目标是计算出如果我这样调用 malloc 将分配多少内存

int *allocated_mem = malloc(2U * 1024U);

并在一个简短的程序中证明我的答案是我尝试过的

printf("Size of 2U: %ld\n", sizeof(2U));
printf("Size of 1024U: %ld\n", sizeof(1024U));

我希望第一行的大小为 2 * 4 Bytes = 8,第二行的大小为 1024 * 4 Bytes = 4096,但输出始终为“4”。

真的很想知道 2U 和 1024U 的确切含义吗?我如何在 C 语言中检查它们的大小?

My goal would be to figured out how much memory will be allocated if i call malloc like this int *allocated_mem = malloc(2U * 1024U);

2 * 1024 == 2048 有什么难的?它们是无符号文字这一事实不会改变它们的值。


An unsigned intagers size is 4 bytes. (sic)

你是对的。所以2U占用4个字节,1024U占用4个字节,因为它们都是无符号整数。


I would have expeted for the first line a size of 2 * 4 Bytes = 8 and for the second like 1024 * 4 Bytes = 4096 but the output is always "4".

为什么值会改变大小?大小仅 取决于类型。 2Uunsigned int类型,所以占4个字节;与 50U 相同,与 1024U 相同。它们都占用 4 字节

您正在尝试将值 (2) 乘以类型的大小。这没有意义。

How big?

2U1024U大小相同,一个unsigned的大小,一般是32位或者4个"bytes"。类型的大小在整个给定平台上都是相同的 - 它不会因为 value 而改变。

"I know that the U literal means in c, that the value is a unsigned integer." --> 好的,到目前为止已经很接近了。

"An unsigned integers size is 4 bytes."。合理的猜测,但 C 要求 unsigned 至少是 16 位。此外,U 使常量 无符号 ,但它可能是 unsignedunsigned longunsigned long long,具体取决于 价值和平台。

详细信息:在 C 中,2U 不是 文字 ,而是 常量 。 C 有 字符串文字 复合文字 。文字可以使用它们的地址,但 &2U 无效 C. 其他语言将 2U 称为 文字 ,并有关于如何使用它的规则.

My goal would be to figured out how much memory will be allocated if i call malloc like this int *allocated_mem = malloc(2U * 1024U);

相反,使用 size_tunsigned 更好地调整大小并检查分配。

size_t sz = 2U * 1024U;
int *allocated_mem = malloc(sz);
if (allocated_mem == NULL) allocated_mem = 0; 
printf("Allocation size %zu\n", allocated_mem);

(旁白)小心计算尺寸。使用 size_t 类型计算尺寸。 4U * 1024U * 1024U * 1024U 可能会溢出 unsigned 数学运算,但可以根据需要使用 size_t.

进行计算
size_t sz = (size_t)4 * 1024 * 1024 * 1024;

以下尝试打印常量的 size 可能是 32 位或 4 "bytes" 而不是它们的 values.

printf("Size of 1024U: %ld\n", sizeof(1024U));
printf("Size of 1024U: %ld\n", sizeof(2U));