指针的大小由malloc分配 [英] size of a pointer allocated by malloc

查看:316
本文介绍了指针的大小由malloc分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

char* pointer;
pointer = malloc (20000);

printf("%d", sizeof(pointer));
//output: 8

我期待为20000的输出,因为我保留20000个字节使用malloc。
但是,它返回8.为什么会出现这种情况?

I was expecting 20000 for the output since I reserved 20000 bytes with malloc. But, it returned 8. Why is this happening?

推荐答案

您必须使用64位系统/ OS,这就是为什么它印8的printf(%D的sizeof(指针));

you must be using 64 bit system/OS, thats why it printed 8 for printf("%d", sizeof(pointer));

当你声明的char * p;它会在你的内存预留空间equalto的sizeof(字符*)。

when you declare char *p; it will reserve space equalto sizeof(char *) in you memory.

现在,如果系统是64位它会预留8字节或者如果它是32位的,然后它会预留的4个字节。

now if the system is 64-bit it will reserve 8 bytes or if it is 32-bit then it will reserve 4 bytes.

现在

char* pointer;
pointer = malloc (20000);

当你定义指针=的malloc(20000)将预留的20000字节的块在内存中的指针指向块的第一个字节它不中分配20000字节的指针。

when you define pointer = malloc(20000) it will reserve a block of 20000 bytes in memory where pointer points to the first byte of that block it doesnt allocates 20000 bytes to pointer.

这篇关于指针的大小由malloc分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆