sizeof 在 malloc 中的作用

Role of sizeof in malloc

提问人:LIsa 提问时间:8/20/2022 最后编辑:LIsa 更新时间:8/20/2022 访问量:160

问:

我的分配部分有效。但是,我不明白.另外,我认为正确的用法是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]);
 }
c malloc dynamic-memory-allocation 大小

评论

0赞 Iłya Bursov 8/20/2022
要分配多少个字节? (哪个是元素数)或 - 哪个是字节数?numnum * 2
0赞 Iłya Bursov 8/20/2022
顺便说一句,用于未签名的 int(4 字节),而不是无符号短整型(2 字节)%u
1赞 Iłya Bursov 8/20/2022
(unsigned short)num执行从类型转换为无符号短整型,但 num 已经是无符号短整型,因此它执行...无num
0赞 LIsa 8/20/2022
@I łyaBursov 为什么引用 num de 然后投射到正确的 lline 中。
1赞 Iłya Bursov 8/20/2022
任何地方都没有 num 取消引用,是乘法,你通过单个元素的大小(以字节为单位)来计算多个元素,从而得到以字节为单位的总大小*

答:

2赞 Mark Ransom 8/20/2022 #1

参数 to 是要分配的字节数。您正在尝试返回一个 with 元素数组。要获得正确的大小,您需要将单个元素的大小乘以元素的数量。你正确的工作陈述正是这样做的;不是取消引用,而是乘法。mallocunsigned shortnumsizeof(unsigned short)num*

评论

0赞 LIsa 8/20/2022
很清楚,非常感谢。