gpt4 book ai didi

C sizeof计算运行时、编译时

转载 作者:行者123 更新时间:2023-11-30 19:01:08 25 4
gpt4 key购买 nike

enter image description here

我认为指针大小可以在编译时计算,因为你应该在编译时指定32位编译或64位编译。

但是既然如此,为什么 sizeof 在运行时计算呢?

https://en.wikipedia.org/wiki/Sizeof

在维基百科中,它说,sizeof 在运行时计算灵活数组,大多数在编译时计算。

最佳答案

在这两种情况下,sizeof 的结果在编译时就已知。在第一种情况下,它是 int * 的大小,在第二种情况下,它是长度为 10 的 int 数组的大小。

幻灯片似乎认为第一种情况下的 sizeof 将为您提供分配的内存量,但事实并非如此。用户必须跟踪分配了多少空间以确保不超出界限。

在运行时计算 sizeof 的唯一时间是针对可变长度数组,例如:

int x = foo();
int arr[x];
printf("size=%zu\n", sizeof(arr));

此行为由 C standard 的第 6.5.3.4p2 节规定。 :

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

关于C sizeof计算运行时、编译时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58358151/

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