堆变量是全局变量,堆变量的范围和生命周期是什么

Anu*_*rma 3 c scope initialization lifetime dynamic-memory-allocation

#include<stdio.h>
#include<conio.h>
#include<alloc.h>

int * makearray(int );
void readdata(int *,int );
void printdata(int *,int );

void main()
{
    int *a,num;
    clrscr();
    printf("enter the size of array\n");
    scanf("%d",&num);
    a=makearray(num);
    readdata(temp,num);
    printdata(a,num);
    getch();
}

int * makearray(int n)
{
    int *temp;
    temp=(int *)malloc(sizeof(int)*n);
    printf("address of temp is %x and value of temp is %d and first value of            temp is garbage i.e %d\n",&temp,temp,*temp);
    return temp;
}

void readdata(int *x,int n)
{
    for(n--; n>=0; n--)
    {
        printf("enter the value in cell[%d]\n",n);
        scanf("%d",x+n);
    }
    return;
}

void printdata(int *x,int n)
{
    for(n--; n>=0; n--)
        printf("the value in cell[%d] is %d",n,*(x+n));
    return;
}
Run Code Online (Sandbox Code Playgroud)

在下面的代码我想知道,因为堆变量的范围如果在程序的持续时间内为什么在程序中temp显示为未识别的符号?

另外我想知道堆变量的生命周期和范围是什么.

另外我想要知道,因为变量在内存中保留了一个空格,只有在我们返回指针时初始化它才会temp被初始化,但temp之后会发生什么呢?它是保持初始化还是被释放.

Sou*_*osh 5

我认为你混淆了两个概念,范围和生命周期.

引用C11,第6.2.1章

对于标识符指定的每个不同实体,标识符仅在称为其范围的程序文本的区域内可见(即,可以使用).[...]

对象的生命周期是程序执行的一部分,在此期间保证为其保留存储.存在一个对象,具有一个常量地址,33)并在其整个生命周期内保留其最后存储的值.[....]

这里的问题是,标识符temp具有块功能范围makearray().由temp(指针)保存的值由内存分配器函数返回,因此显然它有一个liferime,直到它被释放,但这并不意味着temp变量本身具有文件范围.

您已使用另一个变量a来存储返回值makearray(),因此请使用它.