Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof() of an array with random length

Tags:

c

random

gcc

sizeof

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

like image 747
zoli2k Avatar asked Aug 17 '11 13:08

zoli2k


2 Answers

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

like image 182
Andreas Brinck Avatar answered Oct 29 '22 04:10

Andreas Brinck


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.

like image 25
pmg Avatar answered Oct 29 '22 05:10

pmg