Realloc功能无法正常工作?

use*_*802 2 c memory memory-management sizeof realloc

为什么以下代码输出4次,而不是8次和20次?谢谢

int size = 0;
int *pointer;
pointer = malloc(2 * sizeof(int));
size = sizeof(pointer);
printf("%d", size);
int *temp = realloc(pointer, 5 * sizeof(int));
if (temp != NULL) //realloc was successful
{
    pointer = temp;
} else //there was an error
{
    free(pointer);
    printf("Error allocating memory!\n");
}
size = sizeof(pointer);
printf("%d", size);
Run Code Online (Sandbox Code Playgroud)

Joh*_*ica 7

sizeof是一个编译时运算符,它告诉您变量或类型占用多少空间.你得到的答案是一个常数.在指针的情况下,sizeof告诉您存储内存地址所需的字节数.这通常在32位平台上为4个字节,在64位平台上为8个字节.

它没有告诉你已经分配了多少内存malloc().事实证明,遗憾的是没有标准函数来告诉你分配的内存块的大小.你必须自己跟踪它.