5

I researched a lot of static and dynamic memory allocation but still, there is a confusion that:

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]);
}

Does int a[n] come under static or dynamic memory allocation?

4

3 回答 3

14

C标准没有谈论动态分配(或静态分配,就此而言)。但它确实定义了存储持续时间:静态、自动、线程和分配。这决定了一个对象(一段数据)的寿命(可用)多长时间。

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

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

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

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

于 2017-12-12T21:42:21.920 回答
3

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]生命周期在循环体的末尾结束。

于 2017-12-12T21:35:26.150 回答
1

不,它属于自动分配

于 2017-12-17T02:25:11.123 回答