提问人:LIsa 提问时间:8/20/2022 最后编辑:LIsa 更新时间:8/20/2022 访问量:160
sizeof 在 malloc 中的作用
Role of sizeof in malloc
问:
我的分配部分有效。但是,我不明白.另外,我认为正确的用法是sizeof()
*num
(unsigned short*)num
如果我不使用它,我会得到一些错误,但为什么要使用它。
#include <stdio.h>
#include <malloc.h>
#include <string.h>
unsigned short *reverse_seq(unsigned short num) {
if (num == 0) return NULL;
unsigned short *ret = malloc((unsigned short)num); //Works partially
//unsigned short *ret = malloc(sizeof(unsigned short)*num); //Correct allocation
for (int i = 0; i < num; i++)
ret[i] = num - i;
return ret;
}
int main() {
unsigned short *ret = reverse_seq(4u);
for (unsigned short i = 0; i < 4; ++i)
printf("%u", ret[i]);
}
答:
2赞
Mark Ransom
8/20/2022
#1
参数 to 是要分配的字节数。您正在尝试返回一个 with 元素数组。要获得正确的大小,您需要将单个元素的大小乘以元素的数量。你正确的工作陈述正是这样做的;不是取消引用,而是乘法。malloc
unsigned short
num
sizeof(unsigned short)
num
*
评论
0赞
LIsa
8/20/2022
很清楚,非常感谢。
评论
num
num * 2
%u
(unsigned short)num
执行从类型转换为无符号短整型,但 num 已经是无符号短整型,因此它执行...无num
*