欢迎对我的帖子质量发表任何评论,我是新人。
1)函数结束后temp(pointer)的4字节会被清空吗?
2)(不是来自下面的代码)如果我有指向地址 A 的指针 1 并且我将地址 A 复制到指针 2,我如何释放指针 1(作为 int 的 4 个字节)占用的内存并仅保留新指针 2?
(下面的代码)该代码从用户那里获取一个数字(比如说 4),并使用一个函数来创建一个大小为 4、每个槽中有 1 个数组。
int * Array_K_Size(int number)
{
int *temp;
temp = (int *) calloc(number,sizeof(int));
for ( int i=0; i<number; i++)
temp[i] = 1;
return temp;
}
int main()
{
int number,*ptr=NULL;
printf("Give number: ");
scanf("%i",&number);
ptr = Array_K_Size(number);
for ( int i=0; i<number; i++)
printf("Position %3i of array is: %3i\n",i+1,ptr[i]);
return 0;
}
最佳答案
在函数中
int * Array_K_Size(int number)
{
int *temp;
temp = (int *) calloc(number,sizeof(int));
for ( int i=0; i<number; i++)
temp[i] = 1;
return temp;
}
您动态分配了一个数组并返回了指向其第一个元素的指针。
它的值赋值给指针ptr
ptr = Array_K_Size(number);
也就是指针ptr
获取存储在本地指针temp 中的值的副本。退出函数后,局部变量 temp 将不存在。尽管如此,动态分配的内存在函数之外仍然存在。
要释放分配的内存,您只需调用
free( ptr );
指针 temp
的范围是函数 Array_K_Size
的主体。
指针ptr
的范围是函数main
的主体。
来自C标准(6.2.4对象的存储持续时间)
5 An object whose identifier is declared with no linkage and without the storage-class specifier static has automatic storage duration, as do some compound literals....
和
6 For such an object that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way
指针 temp
和 ptr
都有自动存储持续时间,但每个都在各自的 block 中声明。
关于c - 如果使用函数 i 返回一个在其中创建的指针,函数结束后指针在函数中创建的 4 个字节是否会被释放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57482876/