在C中使用malloc为类型定义的类型分配空间 [英] Using malloc in C to allocate space for a typedef'd type

查看:357
本文介绍了在C中使用malloc为类型定义的类型分配空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定我需要使用什么作为malloc的参数来分配table_allocate(int)函数中的空间.我在想的只是count_table * cTable = malloc(sizeof(count_table *)),但这对size参数没有任何作用.我是否也应该为list_node_t分配空间?以下是我正在使用的工具.

I'm not sure exactly what I need to use as an argument to malloc to allocate space in the table_allocate(int) function. I was thinking just count_table* cTable = malloc(sizeof(count_table*)) , but that doesnt do anything with the size parameter. Am i supposed to allocate space for the list_node_t also? Below is what I am working with.

在.h文件中,我得到了这个签名:

in the .h file I'm given this signature:


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

这是我应该使用的结构:

Here are the structs that I'm supposed to use:


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分配内存.

Also, you must allocate memory for list_node_t also seperately.

除了Clifford指出的为列表节点分配内存的方法外,我认为内存分配也应注意列表节点内部的char *key.

Apart from what Clifford has pointed about allocating memory for the list node, I think the memory allocation should also be taken care for the char *key inside of the list node.

这篇关于在C中使用malloc为类型定义的类型分配空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆