Size of a pointer pointing to a structure [duplicate]

六月ゝ 毕业季﹏ 提交于 2019-12-01 19:20:46

No, the size of the structure is eight bytes because you have two four-byte fields in it, try printing sizeof(int) and sizeof(char *) and see for yourself.

When you do sizeof of a pointer, you always gets the size of the pointer and never what it points to. There is no way (in standard C) to get the size of memory you have allocated with malloc.

Also note that you have undefined behavior in your code, as you change the pointer p_struct so it no longer points to what your malloc call returned. This leads to the undefined behavior when you try to free that memory.

Pointers are always the same size on a system no matter what they're pointing to (int, char, struct, etc..); in your case the pointer size is 4 bytes.

p_struct is a pointer to a struct. Pointers usually take either 4 or 8 bytes. If you wanted to know the size of the struct itself, you would use sizeof (*p_struct).

Note that your code is likely to crash, because you increased p_struct three times, and then call free () on the result, not on the original pointer that malloc returned. Much clearer and safer to write for example

for (i=0; i<3;i++)
{
    p_struct [i]->number = i;
    p_struct [i]->name = "string";
    printf("(*p_struct).number = %d, (*p_struct).name = %s\n", p_struct [i]->number p_struct [i]->name)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!