简体   繁体   English

我如何返回我用malloc分配的指针的大小?

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

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! printf函数只返回4个字节! What is wrong? 怎么了?

Thanks so much!!! 非常感谢!!!

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. 通常不可能获得指针所指向的内存块的大小,如果以后需要它,您必须自己记住它。

On some platforms there is the "msize" function that returns the size of an area allocated by malloc/calloc/strdup. 在某些平台上有“msize”函数,它返回malloc / calloc / strdup分配的区域的大小。 But this is not standard. 但这不是标准。

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 ). malloc分配您请求的所有内存,也可以不分配(并返回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. sizeof()运算符执行您的请求:它告诉您指针的大小 - 指针本身占用内存中的4个字节。

没有错,这是32位平台上任何指针的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM