简体   繁体   English

在c中的main函数中初始化的变量存储在哪里?

[英]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. 在C语言中,我知道使用malloc动态初始化变量时,该变量存储在堆区域中。 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. 我最初的理解是像在Java中一样,这里在main函数中声明的所有变量也都存储在堆栈区域中。 My doubt is- Say, there is a function that takes the address of array "a" and changes its contents. 我的怀疑是-说,有一个函数采用数组“ a”的地址并更改其内容。 To change the contents of "a", it should be able to access each element's address in "a". 要更改“ a”的内容,它应该能够访问“ 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. 由于函数本身正在主函数顶部的堆栈空间中执行,因此它无法直接访问数组“ a”的内容。 So, my doubt is where is array "a"'s memory allocated? 因此,我的疑问是数组“ a”的内存分配在哪里?

Usually, int a[n]; 通常, int a[n]; is called a variable length array, and the storage allocation is compiler dependent. 称为可变长度数组,并且存储分配取决于编译器。

For example, gcc allocates VLAs in stack memory . 例如, gcc在堆栈内存中分配VLA

FWIW, the local variables are also usually stored in stack memory (minus the compiler optimization, if any). FWIW,局部变量通常也存储在堆栈内存中(减去编译器优化,如果有的话)。

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 存储在计算机物理内存中的阵列大小

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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