gpt4 book ai didi

c - unsigned int 的内存分配(calloc、malloc)

转载 作者:太空宇宙 更新时间:2023-11-04 06:30:49 25 4
gpt4 key购买 nike

对于我的 C 应用程序,我尝试初始化内存。我知道较慢的 calloc,但幸运的是不需要跟踪性能。

我只需要一个 unsigned int 元素的内存空间(最多 65535)。

这是我的代码中不起作用的部分:

//Declaration
unsigned int part1;

//Allocation
part1 = (unsigned int) calloc (1,sizeof(unsigned int));

这会引发编译器警告:

warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]

为什么上面的代码不起作用,哪里...

unsigned long size;
size =(unsigned long) calloc (1,sizeof(unsigned long));

...效果很好吗?

谢谢!

最佳答案

calloc返回 void* 所以你应该像这样使用它

unsigned int* part1 = calloc (1,sizeof(*part1));

然后像这样赋值

*part1 = 42;

如果你为多个元素分配了空间

part1[0] = 42; // valid indices are [0..nmemb-1]

可能更清楚。

请注意,稍后您还必须释放此内存

free(part1);

或者,如果您只需要一个元素,只需在堆栈上声明它

unsigned int part1 = 42;

关于为什么将一个点转换到 unsigned long 不会产生警告,sizeof(void*)==sizeof(unsigned long) 在您的平台上。如果您依赖于此,您的代码将无法移植。更重要的是,如果您使用指针来存储单个整数,就会泄漏新分配的内存,并且永远无法存储数组中的多个元素。

关于c - unsigned int 的内存分配(calloc、malloc),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20739989/

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