Resize the operator while you work?

A statement sizeofis a compile-time statement, but in the program below it changes at run time.

#include <stdio.h>

void func (int i) { 
    int a[i]; 
    printf("%d \n", sizeof(a)); 
} 

main() { 
    int i = 0; 
    while(i <= 5) { 
        func(i); 
        i++; 
    } 
}

memory will be allocated at runtime. how will the compiler calculate the size of the structure with no structure?

+4
source share
3 answers

Your information is out of date. a- an array of variable length; for those sizeofdetermined at runtime. Variable length arrays is a C99 function that did not exist when the source of your information was recorded.

+6
source

VLA is almost the only case where sizeofit is not a compile-time constant.

+2

a[i]is not legal in standard C ++, although it is supported as an extension by some compilers (for example, GCC documents it here ) - such an extension can streamline any behavior that it likes for the operator sizeof, but it would be most reasonable to base it on the behavior of C.

+1
source

All Articles