How I return the size of the pointer that I have allocate with malloc?

巧了我就是萌 提交于 2019-12-19 10:41:06

问题


See this example!



int main( int argc, char ** argv )
{
    int *ptr = malloc(100 * sizeof (int));

    printf("sizeof(array) is %d bytes\n", sizeof(ptr));
}

The printf function return only 4 bytes! What is wrong?

Thanks so much!!!


回答1:


Nothing is wrong. You are asking for, and getting, the size of the pointer on your platform.

It is not in general possible to get the size of the memory block that a pointer points at, you must remember it yourself if you need it later.




回答2:


On some platforms there is the "msize" function that returns the size of an area allocated by malloc/calloc/strdup. But this is not standard.




回答3:


You cannot print the size of the memory block you received. Either malloc allocates all the memory you requested or it does not (and returns NULL).

The sizeof() operator does what you request: it tells you the size of the pointer - and the pointer itself occupies 4 bytes in memory.




回答4:


Nothing is wrong, that's the size of any pointer on a 32 bit platform.



来源:https://stackoverflow.com/questions/2478240/how-i-return-the-size-of-the-pointer-that-i-have-allocate-with-malloc

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