Difference between sizeof(*p) and sizeof(p)?

こ雲淡風輕ζ 提交于 2021-02-05 07:27:05

问题


I am using code below and getting different values.

int *p;

printf("Size of *p = %d", sizeof(*p));   // Here value is 4

printf("Size of p = %d", sizeof(p));    // Here value is 8

Can any one please explain, what exactly is the reason behind this?


回答1:


For any pointer variable p, the variable p itself is the pointer and the size of it is the size of the pointer. *p is what p is pointing to, and the size of *p is the size of what is being pointed to.

So when sizeof(p) reports 8 then you know that a pointer on your system is 8 bytes, and that you're probably on a 64-bit system.

If sizeof(*p) reports 4 then you know that the size of int (which is what p is pointing to in your case) is 4 bytes, which is normal on both 32 and 64 bit systems.

You would get the same result by doing sizeof(int*) and sizeof(int).

Oh and a last note: To print the result of sizeof (which is of type size_t) then you should really use the "z" prefix, and an unsigned type specifier (since size_t is unsigned). For example "%zu". Not doing that is technically undefined behavior.




回答2:


sizeof(*p) returns size of type what the pointer points to while sizeof(p) returns size of pointer itself.

In your case *p = int and sizeof(int) = 4 on your machine, while you need 8 bytes to store memory address (address where p points to).




回答3:


sizeof(p) is the size of the pointer itself. It depends on the size of the address bus. Which means for a 64-bit system, the address bus size will be 64-bit (8 bytes) so pointer will be 8 bytes long (that shows your system is 64-bit). And on a 32-bit system, it's size will be 32-bit(4 bytes).

sizeof(*p) is the size of pointer type i.e. int here. So usually int is of 32-bit long that is 4 bytes.



来源:https://stackoverflow.com/questions/51870115/difference-between-sizeofp-and-sizeofp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!