C sizeof计算运行-time,compile-time
C sizeof calculation run-time, compile-time
我认为指针大小可以在编译时计算,因为你应该在编译时指定32位编译或64位编译。
但那样的话,为什么 sizeof 的计算时间是 运行 呢?
https://en.wikipedia.org/wiki/Sizeof
在维基百科中它说,sizeof 在 运行 时间内计算灵活的数组,大部分在编译时。
在这两种情况下,sizeof
的结果在编译时是已知的。在第一种情况下,它是 int *
的大小,在第二种情况下,它是长度为 10.
的 int
数组的大小。
幻灯片似乎认为 sizeof
在第一种情况下会给您分配的内存量,但事实并非如此。用户必须跟踪分配了多少 space 以确保不超出范围。
唯一一次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.
我认为指针大小可以在编译时计算,因为你应该在编译时指定32位编译或64位编译。
但那样的话,为什么 sizeof 的计算时间是 运行 呢?
https://en.wikipedia.org/wiki/Sizeof
在维基百科中它说,sizeof 在 运行 时间内计算灵活的数组,大部分在编译时。
在这两种情况下,sizeof
的结果在编译时是已知的。在第一种情况下,它是 int *
的大小,在第二种情况下,它是长度为 10.
int
数组的大小。
幻灯片似乎认为 sizeof
在第一种情况下会给您分配的内存量,但事实并非如此。用户必须跟踪分配了多少 space 以确保不超出范围。
唯一一次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.