Malloc 大空间的结构并像 c 中的数组一样访问它



我正在处理实现哈希表的问题。我对哈希表的理解是,拥有一个像表这样的数组,您可以通过获取哈希值并按表大小对其进行修改来快速访问元素。所以我最初的想法是宣布

Node *hTable [100];

哪里

typedef struct node {
    char *s; 
    int value;
} Node;

转到数组的索引并 malloc 属于那里的新元素。但是,问题是我需要增加我的桌子。

所以,我的问题是,我将如何制作一个动态表,但像数组一样访问它?(例如table[i])。

我知道你需要打电话给类似的东西

Node *table = (Node*)malloc(sizeof(Node)*size);

这使您可以像表一样访问它table[i] =...但是如果我这样做,我将无法在表的索引中声明新的节点

table[i]=(Node*)malloc(sizeof(Node));

这是我一直在测试的代码(获得 seg 错误),以更好地提供问题视图:

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3
  4 typedef struct node {
  5         int data;
  6         struct node *next;
  7 } Node;
  8
  9
 10 void main() {
 11         Node **list;
 12         *list = (Node*)malloc(sizeof(Node)*10);
 13         for (int i = 0; i < 10; i++) {
 14                 list[i] = (Node*)malloc(sizeof(Node)); //problem here?
 15                 list[i]->data = i;
 16                 list[i]->next = NULL;
 17         }
 18         printf("printing...n");
 19         for (int i = 0; i < 10; i++) {
 20                 printf("%d ", list[i]->data);
 21         }
 22 }

您的问题是如何为list分配空间。 list未初始化且未指向有效内存,则必须首先为其分配空间,然后为每个元素分配空间:

#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
    int data;
    struct node *next;
} Node;

int main() //return type of main is int
{
    Node **list;
    list = malloc(10 * sizeof *list); //allocate memory for list not *list, also no need to cast return value of malloc.
    for (int i = 0; i < 10; i++)
    {
        list[i] = malloc(sizeof *list[i]); //allocate space for each element.
        list[i]->data = i;
        list[i]->next = NULL;
    }
    printf("printing...n");
    for (int i = 0; i < 10; i++)
    {
        printf("%d ", list[i]->data);
    }
    return 0;
}

它不需要是一个指针数组,你可以简单地创建一个节点数组,使用:

Node *list = malloc(sizeof *list * count);

然后你可以访问 list[i].slist[i].value .

当您想要增加表时,您可以使用realloc()

new_list = realloc(list, sizeof *list * new_count);
if (new_list) {
    list = new_list;
} else {
    // report allocation failure
}
 #include <stdio.h>
 #include <stdlib.h>
 typedef struct node {
         int data;
         struct node *next;
 } Node;

 int main() {
         // just initialize it this way ( previous was undefined behavior, dereferencing an initialize pointer)
         Node **list= malloc(sizeof(Node*)*10);
         for (int i = 0; i < 10; i++) {
                 list[i] = malloc(sizeof(Node*)); //problem here?
                 list[i]->data = i;
                 list[i]->next = NULL;
         }
         printf("printing...n");
         for (int i = 0; i < 10; i++) {
                 printf("%d ", list[i]->data);
          }
 }

最新更新