_X_l 2021-08-07 15:53 采纳率: 80%
浏览 38
已结题

c语言malloc函数构造数组失败


    hfmnode *ht = (hfmnode *)malloc(16*sizeof(hfmnode));
    //printf("%d", sizeof(*ht);
    for (int i = 0; i < 2 * n; i++) {
        ht[i].weight = 0;
        ht[i].lchild = 0;
        ht[i].rchild = 0;
        ht[i].perant = 0;
    }

我用malloc函数构造一个大小为16个hfmnode结构体的数组,但是后面赋值的时候只有一个结构体。

  • 写回答

1条回答 默认 最新

  • 我素wfz 2021-08-07 16:51
    关注

    #include <stdio.h>
    #include<stdlib.h>
    int main(){
    typedef struct
    {
    int weight;
    int lchild;
    int rchild;
    int perant;
    }hfmnode;
    int n=1;
    hfmnode *ht = (hfmnode )malloc(16sizeof(hfmnode));
    /*printf("%d", sizeof(ht);/
    for (int i = 0; i < (2 * n); i++) {
    ht[i].weight = 0;
    ht[i].lchild = 0;
    ht[i].rchild = 0;
    ht[i].perant = 0;
    }
    for (int i = 0; i < 2 * n; i++)
    {
    printf("%d,%d,%d,%d\n",ht[i].weight,ht[i].lchild,ht[i].rchild,ht[i].perant);
    }

    return 0;
    

    }
    我为你的代码做了补充,发现应该是没有错误的。如果你的依旧出错的话,就把我的给写上吧

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 8月15日
  • 已采纳回答 8月7日
  • 创建了问题 8月7日

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler