我在访问节点的子数组时遇到问题。我写了两个结构,其中一个包含另一个。我无法访问子数组的第一个节点以外的地方。
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.
}
我的总体目标是拥有一系列链接列表。不确定为什么这种方法行不通。
答案 0 :(得分:1)
要拥有链接列表数组,您需要创建一个指向链接列表第一个节点的指针数组。
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;
}
答案 1 :(得分:0)
您应该阅读手册页malloc(3),尤其是calloc()部分。
仅将指针放在结构中并神奇地假设会有数组是不够的。您必须使用该手册页中描述的功能为其保留内存。而且更重要的是,当您不再需要保留的内存时,必须free()
。
此外,您还应考虑将数组的长度作为结构的一部分。 像这样:
struct node{
int distance;
int destination;
int weight;
node *adj;
size_t adj_count;
};
struct adjList{
struct node *node;
size_t node_count;
adjList *next; // I renamed this member to next,
// which makes it more clear that this is a linked list
};
编辑:编辑问题后,突然有一个malloc(),但是肯定是错误的。否则,您对数据结构的命名会产生误导。