gpt4 book ai didi

c - 如何访问堆上的数组链表?

转载 作者:太空宇宙 更新时间:2023-11-04 03:11:48 24 4
gpt4 key购买 nike

我在访问节点的子数组时遇到问题。我写了两个结构,其中一个包含另一个。我无法访问超出子数组第一个节点的内容。

struct node{
int distance;
int destination;
int weight;
node *adj;
};

struct adjList{
struct node *node;
adjList *array;
};// adjList a is made out of an array of "nodes". Essentially each element in the adjList a should have a pointer to a subarray of "nodes" that i can access.


a=(adjList*) malloc(numOfNodes * sizeof(struct adjList));//allocate space for array of linked lists


for(int j=0; j<numOfNodes; j++){
array[j].node=malloc(numOfEdges * sizeof(struct node));//allocate space for each linked list in the array
}


for(int j=0; j<numOfNodes; j++){
a[j].node->adj[j]=NULL; //trying to set the "jth's" element of the adjacencylist's "jth" node. This syntax does not work as the compiler wont let me even use it.
}

我的整个目标是拥有一个链表数组。不确定为什么此方法不起作用。

最佳答案

要拥有链表数组,您需要创建一个指向链表第一个节点的指针数组。

struct node **array = malloc(sizeof(struct node*) * arraySize /* numOfNodes */);

现在 array[i] 将指向 ith<​​ 链表。

for(int i=0; i<arraySize ; i++){
struct node *head = NULL;
/* Allocate nodes for ith linked list */
for(int j=0; j<numOfNodes; j++) {
if(0 == j) {
array[i] = malloc(sizeof(struct node)); //First node of ith linked list
memset(array[i], 0, sizeof(struct node)); //OR you can use calloc. Required to remove junk pointers in node.
head = array[i];
} else {
head->adj = malloc(sizeof(struct node)); /* Allocate jth node */
memset(head->adj, 0, sizeof(struct node)); //OR you can use calloc. Required to remove junk pointers in node.
head = head->adj;
}
}
}

你可以遍历 ith<​​ 个链表,如下所示。

struct node *head = array[i];
while(head) {
printf("\ndist %d dest %d weight %d\n", head->distance, head->destination, head->weight);
head = head->adj;
}

关于c - 如何访问堆上的数组链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55626050/

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