加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在C中使用malloc为typedef类型分配空间

发布时间:2020-12-16 10:17:57 所属栏目:百科 来源:网络整理
导读:我不确定我需要使用什么作为malloc的参数来在table_allocate(int)函数中分配空间.我只想到count_table * cTable = malloc(sizeof(count_table *)),但这对size参数没有任何作用.我应该为list_node_t分配空间吗?以下是我正在使用的内容. 在.h文件中我给了这个
我不确定我需要使用什么作为malloc的参数来在table_allocate(int)函数中分配空间.我只想到count_table * cTable = malloc(sizeof(count_table *)),但这对size参数没有任何作用.我应该为list_node_t分配空间吗?以下是我正在使用的内容.

在.h文件中我给了这个签名:

//create a count table struct and allocate space for it                         
//return it as a pointer                                                        
count_table_t* table_allocate(int);

以下是我应该使用的结构:

typedef struct list_node list_node_t;

struct list_node {
  char *key;
  int value;

  //the next node in the list                                                   
  list_node_t *next;
};

typedef struct count_table count_table_t;

struct count_table {
  int size;
  //an array of list_node pointers                                              
  list_node_t **list_array;
};

谢谢!

解决方法

count_table* cTable = malloc(sizeof(count_table*))

是错的.它应该是

count_table* cTable = malloc(sizeof(count_table));

此外,您还必须单独为list_node_t分配内存.

编辑:

除了Clifford指出的为列表节点分配内存之外,我认为内存分配也应该注意列表节点内的char *键.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读