我很好奇为什么我在我的代码中得到以下行为.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int M=24;
int arr[M];
int N=24;
int* ptr=(int*) malloc(sizeof(int)*N); /*Allocate memory of size N */
printf("Size of your malloced array is %lu\n",sizeof(ptr)/sizeof(ptr[0])); /* Get the size of memory alloctaed. Should be the same as N?*/
printf ("Size of your normal arrays is %lu\n",sizeof(arr)/sizeof(arr[0])); /* Ditto */
free(ptr);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是
Size of your malloced array is 2
Size of your normal arrays is 24
Run Code Online (Sandbox Code Playgroud)
我原以为输出会24在两个地方都有.然后如何获得malloced数组的大小如果我以某种方式"忘记"了它?
当然,指针ptr将包含一些关于malloced数组大小的信息,因为当我们调用free(ptr)它时将释放数组只是malloced
当您sizeof()在指针上使用时,您将获得指针的大小.不是分配的数组的大小.在你的情况下,指针可能是8个字节,一个int是4个字节,因此为什么你得到2.
简而言之,您无法获得已分配数组的大小.你需要自己跟踪它.
编辑:请注意,一些编译器确实支持此功能作为扩展:
例如,MSVC支持_msize():http://msdn.microsoft.com/en-us/library/z2s077bc.aspx