这是静态内存分配还是动态内存分配的例子?

Is this is an example of static memory allocation or dynamic memory allocation?

我研究了很多静态和动态内存分配,但仍然有一个困惑:

int n, i, j;
printf("Please enter the number of elements you want to enter:\t");
scanf("%d", &n);
int a[n];
for (i = 0; i < n; i++)
{
    printf("a[%d] : ", i + 1);
    scanf("%d", &a[i]);
}

int a[n] 属于静态还是动态内存分配?

int a[n]为自动存储时长的变长数组,

考虑以下演示程序。

#include <stdio.h>
#include <string.h>

int main(void) 
{
    const size_t N = 10;

    for ( size_t i = 1; i <= N; i++ )
    {
        char s[i];

        memset( s, '*', sizeof( s ) );

        printf( "%*.*s\n", ( int )i, ( int )i, s );
    }

    return 0;
}

它的输出是

*
**
***
****
*****
******
*******
********
*********
**********

每次将控件传递给循环体时,编译器代码生成的都会创建一个本地数组s[n],其生命周期在循环体结束时结束。

C 标准不讨论动态分配(或静态分配)。但它确实定义了存储 durations:静态、自动、线程和已分配。这决定了一个对象(一段数据)存在多长时间(可用)。

  • Static 在存储持续时间的意义上意味着该对象可用于整个程序的执行。文件范围内的变量('global' 变量)和声明中带有 static 的局部变量具有静态存储持续时间。

  • Automatic 存储持续时间是您的常规局部变量,它们仅在声明它们的块的持续时间内存在(函数,或在 curly例如 for 循环的大括号).

  • Allocated存储时长是指通过malloc和好友获得的内存。从(成功)调用 malloc 开始,直到相应的调用 free。这通常被称为动态内存分配,因为它是一种获得大小在 运行 时确定的内存块的方法。

您的变量 a 具有自动存储期限。然而,它可以被认为是动态的,因为它的长度是在 运行 时而不是编译时确定的。就像分配的存储持续时间一样。

不,它属于自动分配