编辑
2025-04-14
技术杂谈
00
请注意,本文编写于 114 天前,最后修改于 114 天前,其中某些信息可能已经过时。

This article explains sizeof and variable length array.

In C, sizeof is mostly evaluated at compiler time. However, C99 introduces variable length of array. Thus, in rare cases of variable length array, sizeof is evaluated at runtime.

There comes another question. Where is the length stored? In C99, only a variable array will store its length in an implicit variable.

C
#include <stdio.h> int main(){ int n; scanf("%d", &n); int a[n]; printf("%d\n",sizeof(a)); return 0; }

The corresponding assembly code is like:

asm
movl -76(%rbp), %ecx # Load the value of `n` into %ecx movslq %ecx, %rax # Sign-extend `n` to 64 bits in %rax salq $2, %rax # Multiply `n` by 4 (size of `int`), equivalent to `sizeof(int) * n` movq %rax, %rsi # Store the calculated size