gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:50:15 25 4
gpt4 key购买 nike

我正在处理实现哈希表的问题。我对哈希表的理解是,拥有一个类似于表的数组,您可以通过获取哈希值并根据表大小对其进行修改来快速访问元素。所以我最初的想法是声明

Node *hTable [100];

在哪里

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

然后转到数组的索引并 malloc 一个属于那里的新元素。但是,问题是我需要扩大我的 table 。

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

我知道你需要调用类似的东西

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

这让你可以像访问表一样访问它 table[i] =... 但如果我那样做,我就不能在表的索引中声明一个新节点

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

这是我一直在测试的代码(出现段错误)以更好地了解问题:

  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;
}

关于c - Malloc 结构的大空间并像 c 中的数组一样访问它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54297677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com