简体   繁体   English

了解作用域数组的存储方式

[英]Understanding how scoped arrays are stored

I'm confused how arrays are stored in the executable when they're within functions and the like.我很困惑数组在函数等中时如何存储在可执行文件中。

With the code below I believe space for the value of the three ints to be stored is made in the executable.使用下面的代码,我相信在可执行文件中为要存储的三个整数值的空间。

#include <stdlib.h>

int main() {
    int arr[] = {rand(), rand(), rand()};
}

I was thinking for an array in a function, each call would use the same space as the other calls to store their array.我在考虑函数中的数组,每次调用将使用与其他调用相同的空间来存储它们的数组。 But then I thought recursive calls would overwrite each others arrays.但后来我认为递归调用会覆盖彼此的数组。 I don't get how space for them is left aside, especially with recursion and an unknown number of calls are made.我不明白如何为它们留出空间,尤其是在递归和未知数量的调用中。 I tried to make an example:我试着举个例子:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

bool myfunc(unsigned val) {
    int arr[] = {rand() % 10, rand() % 10};

    if (val == 0)
        return true;

    myfunc(val - 1);

    printf("%d %d\n", arr[0], arr[1]);
    return false;
}

int main() {
    myfunc(rand() % 50);
}

I get arrays elements are stored one after the other.我得到数组元素一个接一个地存储。 But how is there space for them (in the stack?) when it's unkown how many there will be?但是,当不知道会有多少空间时,它们(在堆栈中?)怎么会有空间呢?

Objects defined with local scope in a function body with automatic storage (without a static keyword) are stored in temporary storage and reclaimed automatically upon exiting the corresponding scope.在具有自动存储功能(没有static关键字)的函数体中定义了局部作用域的对象存储在临时存储中,并在退出相应作用域时自动回收。

Typical modern architectures use the runtime stack for this: the stack pointer register is decremented upon entering the scope by a fixed amount if the size is known at compile time, as is the case for your examples: int arr[] = {rand() % 10, rand() % 10};典型的现代架构为此使用运行时堆栈:如果大小在编译时已知,则堆栈指针寄存器在进入作用域时会递减固定数量,就像您的示例一样: int arr[] = {rand() % 10, rand() % 10}; defines an array of 2 int , usually 8 bytes.定义一个 2 个int数组,通常为 8 个字节。

If the size is only known at runtime, the stack pointer is decremented by a value computed at runtime, possibly causing undefined behavior if this size is too large.如果大小仅在运行时已知,堆栈指针将减少一个在运行时计算的值,如果此大小太大,可能会导致未定义的行为。 The stack pointer is restored to its original value upon leaving the function.离开函数时,堆栈指针恢复到其原始值。

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

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