Search code examples
arrayscsizeofc89ansi-c

the size of dynamically allocated array in C


I know that this question has been asked before, but my question is more specific, here is the code:

#include <stdio.h>
#include <time.h>    /* must be included for the time function */

main()
{
    time_t t = time(NULL);
    srand((unsigned) t);

    int i = rand();

    int a[i];

    printf("%d\n", i);        /* ouptut: 18659 */
    printf("%d\n", sizeof a); /* output: 74636 */
}

I compiled this code using gcc and -ansi option to restrict it to recognize the ANSI C only. I know that there is no way that the compiler could know at compile-time the size of the array because it's determined randomly at run-time. Now my question is is the value returned by sizeof is just a random value, or it has a meaning?


Solution

  • The value returned by sizeof is a pseudo-random value that has a meaning:

    • The value represents the size of VLA a, in bytes
    • It is random only in the sense that the number of array elements is determined by a call to rand.

    It appears that sizeof(int) on your system is 4, because the number returned by sizeof is four times the number of elements in the array.

    Note: One of the consequences of allowing VLAs in C99 is that sizeof is no longer a purely compile-time expression. When the argument of sizeof operator is a VLA, the result is computed at run-time.