简体   繁体   中英

where are the variable stored that are initialized in main function in c?

In C language, I know that when a variable is dynamically initialized using malloc, it is stored in heap area. But where is the memory allocated when declaration of below kind is done and variables are initialized later.

int a[26];

or

int a[n]; //n is a variable and each element in array a is later initialized through a for loop.

My initial understanding is that like in java, here also all variables declared in main function are stored in stack area. My doubt is- Say, there is a function that takes the address of array "a" and changes its contents. To change the contents of "a", it should be able to access each element's address in "a". As the function itself is getting executed in the stack space on the top of main function, it cannot access array "a"'s contents directly. So, my doubt is where is array "a"'s memory allocated?

Usually, int a[n]; is called a variable length array, and the storage allocation is compiler dependent.

For example, gcc allocates VLAs in stack memory .

FWIW, the local variables are also usually stored in stack memory (minus the compiler optimization, if any).

arrays can be almost any length, they can be used to store thousands or even millions of objects, but the size must be decided when the array is created. Each item in the array is accessed by an index, which is just a number that indicates the position or slot where the object is stored in the array.

Array size stored in the computer physical memory

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM