gpt4 book ai didi

c - Realloc 函数无法正常工作?

转载 作者:行者123 更新时间:2023-12-04 09:15:54 27 4
gpt4 key购买 nike

为什么下面的代码输出两次 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);

最佳答案

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

它不会告诉您 malloc() 分配了多少内存。事实证明,不幸的是没有标准函数可以告诉您分配的内存块的大小。您必须自己跟踪它。

关于c - Realloc 函数无法正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20890700/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com