Search code examples
csizeof

C sizeof calculation run-time, compile-time


enter image description here

I think pointer size can be calculated in compile-time because you should specify 32bit compile or 64bit compile at compile-time.

But in that case, why sizeof calculated in run-time?

https://en.wikipedia.org/wiki/Sizeof

In wikipedia it says, sizeof caculate flexible array in run-time, most in compile-time.


Solution

  • In both of these cases the result of sizeof is known at compile time. In the first case it is the size of an int * and in the second case it is the size of an int array of length 10.

    The slide seems to think that sizeof in the first case will give you the the amount of memory allocated, however this is not true. The user must keep track of how much space was allocated to ensure that the bounds are not exceeded.

    The only time sizeof is calculated at run time is for a variable length array, for example:

    int x = foo();
    int arr[x];
    printf("size=%zu\n", sizeof(arr));
    

    This behavior is dictated by section 6.5.3.4p2 of the C standard:

    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.