c - 为什么这个 malloc 在 C 中不起作用?

标签 c pointers malloc

只是想做一种哈希表,每个节点都是一个链表。

初始化空间时遇到问题,我做错了什么?

#include <stdlib.h>

typedef struct entry {
 struct entry *next;
 void *theData;
} Entry;


typedef struct HashTable {
 Entry **table;
 int size;
} HashTable;

int main(){
 HashTable *ml;
 ml = initialize();
 return 0;
}

HashTable *initialize(void)
{
 HashTable *p;
 Entry **b;
 int i;


 if ((p = (HashTable *)malloc(sizeof(HashTable *))) == NULL)
  return NULL;
 p->size = 101;

 if ((b = (Entry **)malloc(p->size * sizeof(Entry **))) == NULL)
         return NULL;

 p->table = b;

 for(i = 0; i < p->size; i++) {
  Entry * b =  p->table[i];
  b->theData = NULL;
  b->next = NULL;
     }

 return p;
}

最佳答案

您需要将 sizeof(HashTable*) 更改为 sizeof(HashTable) 并且同样将 sizeof(Entry **) 更改为 sizeof(条目 *) 。第二件事是对于每个 Entry,您需要在循环内再次使用 malloc 分配内存。

关于c - 为什么这个 malloc 在 C 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4023098/

相关文章:

c - 如何调试用 cgo 调用的 C 代码?

c - 为嵌套链表分配内存+使用scanf

c - 字符串文字如何等于 char*,以及我应该如何将字符串作为参数

linux - 如何分配 4k 对齐的内存

C 中的 Char 数组串联格式

c - c中的所有函数都是全局定义的,那么为什么我们需要将它们作为参数传递给函数呢?

c++ - 在 qsort() 中类型转换

c++ - 如何检查对象是否在数组中?

c - 最小化 malloc() 调用量可以提高性能?

C通用链表