Example 1 — A VLA sized by a variable
Fill with squares and report the run-time size.
#include <stdio.h>
int main(void) {
int n = 4;
int sq[n];
for (int i = 0; i < n; i++) {
sq[i] = i * i;
}
for (int i = 0; i < n; i++) {
printf("%d ", sq[i]);
}
printf("\nsizeof sq = %zu\n", sizeof sq);
return 0;
} How It Works
nis a variable, sosqis a VLA.- There is no initializer list; elements are filled by the loop.
sizeof sqis computed at run time: 4 ints * 4 bytes = 16.
