指针变量在内存中是如何分配的?内存分配取决于数据类型吗?
void main
{
int a,*b;
a=10;
a=&b;
printf("value of a %d",a);
printf("value of b %d",b);
}
指针变量在内存中是如何分配的?内存分配取决于数据类型吗?
void main
{
int a,*b;
a=10;
a=&b;
printf("value of a %d",a);
printf("value of b %d",b);
}
How are pointer variables allocated in memory? Does the memory allocation depend on datatype?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它们的分配方式与(例如)整数相同。他们所指向的事物的类型对此没有影响。
They are allocated in the same way that (for example) integers are. And the type of the thing they point to has no effect on that.
这个特定的指针被分配在堆栈上,因为它是一个自动变量。这与“普通”非指针变量没有什么不同。如果“内存分配”指的是分配的大小,那么是的,指针的大小可能取决于受指点类型。
您可以使用
sizeof
找出指针的大小。在本例中,b
占用sizeof(int *)
字节,该字节取决于平台(在现代机器上通常为 4 或 8 字节)。如果需要,您可以在自由存储(堆)上分配一个指针:(
请注意,顺便说一句,您的示例程序是错误的:
a=&b
应该是b=&a
。)This particular pointer is allocated on the stack, because it is an automatic variable. This is no different from an "ordinary", non-pointer variable. If by "the memory allocation" you mean the size of the allocation, then yes, the size of a pointer may depend on the pointee type.
You can find out the size of a pointer with
sizeof
. In this case,b
takes upsizeof(int *)
bytes, which is platform-dependent (typically 4 or 8 bytes on modern machines).You could allocate a pointer on the freestore (heap) if you wanted:
(Note, btw., that your example program is erroneous:
a=&b
should beb=&a
.)自动分配最终位于堆栈上。动态分配最终位于堆上。不管它是什么数据类型。
Automatic allocation ends up on the stack. Dynamic allocation ends up on the heap. No matter what data type it is.
指针本身就是一个变量,它指向另一个变量。它始终包含它所指向的任何内容的地址。由于地址大小相同,因此所有指针无论指向什么,都具有相同的大小。
pointer is itself a variable which points to other variable. It always contain the address of whatever it is pointing to. As address is of same size, all pointers have same size, no matter what they point to.