为什么 malloc 在我请求 20 个字节时给我 8 个字节?

Why is malloc giving me 8 bytes when I request 20?

我刚刚第一次接触 C 语言,我很困惑为什么 malloc 没有给我预期的内存量。以下代码:

printf("Allocating %ld bytes of memory\n", 5*sizeof(int));
int *array = (int *) malloc(5*sizeof(int));
printf("%ld bytes of memory allocated\n", sizeof(array));

结果:

Allocating 20 bytes of memory
8 bytes of memory allocated

我检查过我确实调用malloc给我20个字节,但不明白为什么调用malloc后,指针只有8个字节。

array 不是数组而是 int *。所以它的大小永远是指针的大小。

sizeof 运算符不会告诉您在指针处动态分配了多少内存。

如果另一方面你有这个:

int array2[5];

然后 sizeof(array2) 将是 20,假设 int 是 4 个字节。

sizeof 运算符告诉您其操作数的大小。 array 的类型 int*(指向 int 的指针)在您的平台上占用八个字节。 sizeof 运算符无法找出数组 array 指向的实际长度。什么是 returns 并不表示已分配多少内存。

malloc() 函数要么失败(在这种情况下它 returns NULL)要么成功,在这种情况下它 returns 一个指向内存区域的指针至少大到你需要的。