繁体   English   中英

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

[英]Using malloc in C to allocate space for a typedef'd type

我不确定我需要使用什么作为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 *key

您的建议: count_table* cTable = malloc(sizeof(count_table*))只会为指向count_table 的指针分配空间。

你需要

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

每个列表节点将被单独分配,并且 cTable->size 和 cTable->list_array 以及最后一个list_node_t::next更新。 维护指向添加的最后一个节点的指针将使添加节点更快。

我不确定为什么count_table::list_array的类型是list_node_t**而不仅仅是list_node_t* (并且同样称为list_array而不仅仅是list )。 您的意图是它同时是一个数组和一个列表吗? 那会有些多余。 该成员只需是指向第一个节点的指针,然后通过list_node::next访问后续节点

鉴于int是创建的count_table_t的“大小”参数,看来您应该既分配count_table_t本身,又初始化其成员。

初始化list_array成员还涉及内存分配,因此它看起来像:

count_table_t *table_allocate(int size)
{
    count_table_t *table = malloc(sizeof *table);
    int i;

    table->size = size;
    table->list_array = malloc(size * sizeof table->list_array[0]);
    for (i = 0; i < size; i++)
        table->list_array[i] = NULL;

    return table;
}

但是,您还需要检查一些错误情况: size乘以sizeof table->list_array[0]可能会溢出,并且malloc()调用可能会失败。 所以这个函数实际上应该是这样的:

count_table_t *table_allocate(int size)
{
    count_table_t *table;
    int i;

    /* Check for overflow in list allocation size */
    if (size < 0 || size > (size_t)-1 / sizeof table->list_array[0])
        return NULL;

    table = malloc(sizeof *table);

    if (table == NULL)
        return NULL;

    table->size = size;
    table->list_array = malloc(size * sizeof table->list_array[0]);

    if (table->list_array == NULL) {
        free(table);
        return NULL;
    }

    for (i = 0; i < size; i++)
        table->list_array[i] = NULL;

    return table;
}

(请注意, (size_t)-1是一个常数,等于size_t最大值,它是malloc()的参数类型)。

除了其他张贴者指出您只为指针分配了足够的空间,而不是您想要的数据将占用的空间之外,我强烈建议您执行以下操作:

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

如果cTable的类型发生变化,这将有助于您,您不必将两个部分调整到该行,只需调整类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM