gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:05:49 24 4
gpt4 key购买 nike

#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;
}

在下面的代码中,由于堆变量的范围,我想知道在程序运行期间,为什么 temp 在程序中显示为未识别的符号?

我还想知道堆变量的生命周期和范围是多少。

我还想知道,由于变量仅在我们返回指针 temp 时被初始化,因此它在内存中保留了一个空间 a 被初始化但是 temp 发生了什么> 在那之后?它是保持初始化还是被释放。

最佳答案

我认为您混淆了两个概念,scope和生命周期。

引用 C11,章节 §6.2.1

For each different entity that an identifier designates, the identifier is visible (i.e., can be used) only within a region of program text called its scope. [...]

The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address,33) and retains its last-stored value throughout its lifetime. [....]

这里的问题是,标识符 temp 具有函数 makearray() 的 block 作用域。 temp 持有的值(一个指针)由内存分配器函数返回,因此很明显它在被释放之前有生命周期,但这并不意味着 temp 变量本身有一个文件范围。

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

关于c - 堆变量是全局变量,什么是堆变量的范围和生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41322716/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com