Dynamically allocating an array on a stack in C

I just conducted an experiment yesterday and found something incomprehensible:

#include <stdio.h>

int main()
{
    int j;
    scanf("%d",&j);
    const int i = j;
    int arr[i];
    return 0;
}

The number is jread from the keyboard and used to allocate an array arron the stack.

The compiler does not even know the size of the array at compile time (initializes j to 0?), But there is no compilation error. How is this possible?

+4
source share
3 answers

Variable length arrays have been added to C99. This is described in explanation C99:

6.7.5.2 Manifest declaration

C99 , . , C . Cs .

, length array type - . C99 .

" ". .

, GCC, C90 ( GCC, ansi C89) ++. (-Wpedantic) (-Werror -pedantic-errors). .

@Deduplicator , , . .

ยง 6.7.6.2

10 EXAMPLE 4 (VM) , . , _Thread_local, static extern (VLA) . , staticspecifier VM ( VLA). , , , ostructures union.

, static storage automatic .

+11

, , . , () alloca():

Alloca

C99 Variable Length Arrays ( "VLA" ) ; " ", :

alloca (n) char x [n]?

, , . , , , . NULL malloc(). , undefined; true :

alloca() ?

+2

C has such a feature as variable-length arrays. In flight, arrays with automatic storage duration can be defined.

+1
source

All Articles