Can you explain how the sizeof()
works with a random length array? I thought sizeof()
on an array is calculated during the compilation, however, the size of an array with random length seems to be calculated correctly.
Example:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main(){
srand ( (unsigned)time ( NULL ) );
int r = rand()%10;
int arr[r]; //array with random length
printf("r = %d size = %d\n",r, sizeof(arr)); //print the random number, array size
return 0;
}
The output from multiple runs:
r = 8 size = 32
r = 6 size = 24
r = 1 size = 4
Compiler: gcc 4.4.3
In C99 sizeof variable sized arrays is computed in runtime. From the C99 draft 6.5.3.4/2:
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
In your code, arr
is a special kind of array: it is a VLA (variable length array).
The paragraph for sizeof in the Standard (6.5.3.4) says
If the type of the operand is a variable length array type, the operand is evaluated
so it's not a compile-time constant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With