The size of a dynamically allocated array in C

I know 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 the gcc and -ansi options to limit it to ANSI C recognition only. I know that the compiler could not know the size of the array at compile time because it was accidentally determined at runtime. Now my question is - is the value returned by sizeof just a random value or does it make sense?

+4
source share
4 answers

The value returned sizeofis a pseudo-random value having the value:

  • VLA a,
  • , rand.

, sizeof(int) 4, , sizeof, .

. VLA C99 , sizeof . sizeof VLA, .

+3

sizeof . VLA .

6.5.3.4 C:

2 sizeof ( ) , . . . - , ;

, , sizeof, - VLA. i * sizeof(int)

+6

- , sizeof, ?

, 74636/18659= 4, , -, int .

So sizeof ( , VLA), a , int it ( i 18659), int, 4 .

i ( rand) , , sizeof .

+2

gcc

-ansi , ISO, . -ansi -Wpedantic.

+2

Source: https://habr.com/ru/post/1676908/


All Articles