我的数据是存储在堆中还是在下面的代码中的堆栈中
在下面的代码中,我通过malloc
获取内存并通过指针ptr
指向它。当我如图所示分配值时,我将数据存储在指针中,我们知道指针位于堆栈帧中。
所以我的问题是:我的数据(整数)存储在堆栈中还是堆中?
#include<stdio.h>
#include<stdlib.h>
void main()
{
int *ptr;
ptr=(int*)malloc(5*sizeof(int));
ptr[0]=5;
ptr[1]=6;
ptr[2]=8;
ptr[3]=10;
ptr[4]=11;
}
In the below code, I get memory through malloc
and pointed it by pointer ptr
. When I assigned value as shown I stored the data in pointer and we know that pointer is located in stack
frame.
So my question is: My data(integers) is stored in stack
or in heap
?
#include<stdio.h>
#include<stdlib.h>
void main()
{
int *ptr;
ptr=(int*)malloc(5*sizeof(int));
ptr[0]=5;
ptr[1]=6;
ptr[2]=8;
ptr[3]=10;
ptr[4]=11;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,指针存储在栈上,但它指向的内存却在堆上。因此,整数存储在堆上。
编辑回答评论中的问题:
在 C 语言中,数组访问是根据指针定义的。所以数组元素访问
ptr[0]
可以写成*ptr
。要访问数组的元素n
,可以编写ptr[n]
或*(ptr+n)
。如果您的数组存储指针并且您想要访问该值,则可以使用
*ptr[0]
。您也可以将其视为二维数组。换句话说,*ptr[0]
相当于ptr[0][0]
。来自 C 标准:
另请参阅此问题:数组名称是指针吗?
Yes, the pointer is stored on the stack, but the memory it points to is on the heap. Therefore, the integers are stored on the heap.
Edit to answer the question from the comments:
In C, an array access is defined in terms of pointers. So the array element access
ptr[0]
can be written as*ptr
. To access elementn
of the array, you can writeptr[n]
or*(ptr+n)
.You would use
*ptr[0]
if your array stored pointers and you wanted to access the value. You can also think of that as a two-dimensional array. In other words,*ptr[0]
is equivalent toptr[0][0]
.From the C standard:
Also see this question: Is an array name a pointer?
迂腐地说,从 C 标准的角度来看,这里涉及的所有对象只是占用一些适当对齐的内存,并且与其他对象脱节。
虽然栈和堆的概念很常见,但 C 标准没有提及这两个术语。数据的存储方式和位置主要是由实现定义的。
区分它们的主要因素是它们的可见性和有效生命周期(请参阅:存储持续时间 、生命周期和范围):
ptr
的使用是在main
返回之前有效。在
malloc
返回的地址处使用内存是有效的直到它被释放。通常是公平的
因为这是 C 实现的一种非常常见的工作方式。
使用这个术语,由标识符
ptr
指定的对象存在于堆栈上,并且通过malloc
返回的指针访问的对象存在于堆栈上。 堆。Pedantically speaking, from the perspective of the C standard, all the objects involved here simply occupy some memory that is suitably aligned, and disjointed from other objects.
While the notion of a stack and heap are commonplace, the C standard makes no reference to either terms. How and where data is stored is mostly implementation-defined.
The principle thing differentiating them is their visibility and effective lifetimes (see: Storage duration, Lifetime, and Scope):
The use of
ptr
is valid untilmain
returns.The use of the memory at the address returned by
malloc
is valid until it is deallocated.Practically speaking, however, it is generally fair to refer to objects with
as this a very common way C implementations work.
With this terminology, the object designated by the identifier
ptr
exists on the stack, and the objects accessed via the pointer returned bymalloc
exist on the heap.