Is this array static or dynamic?

So, I am studying memory allocation, and he said that you can only allocate memory dynamically using malloc (); but this is also not a dynamic memory allocation? it works btw.So I'm a little confused.

#include<stdio.h> #include<conio.h> int main() { int integer,cntr; scanf("%d",&integer); char words[integer]; for(cntr = 0;cntr < integer - 1;cntr++) words[cntr] = 'k'; words[cntr] = '\0'; printf("%s",words); getch(); return(0); } 
+4
source share
3 answers

This is a variable length array . The size is really dynamic, but in practice it is usually allocated on the stack instead of the heap (so don't use it for anything too large).

Depending on your compiler, etc., it will probably be much faster than allocating heap memory, nothing more than adjusting the stack pointer.

Variable-length matrices were introduced in the C99 standard, so keep in mind that you cannot use them with very old C compilers (such as MSVC).

+4
source

The array is a local array , and it will be automatically freed after the area ( { , } ) in which it is defined ends.
Technically, the standard does not determine where it should be allocated, but only defines the characteristics that such an array can offer. The standard doesn't even mention the stack or heap:

+1
source

This is static because the array is allocated on the stack, not on the heap.

It is not allocated by the memory manager, it is simply reserved on the stack, but nothing more. It ceases to exist (in the sense that its use will contain garbage) as soon as it goes beyond.

Remember that since the stack is limited, you cannot allocate such a large array in this way.

0
source

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


All Articles