【问题标题】:Array of Linked List, moving to the next node error;链表数组,移动到下一个节点错误;
【发布时间】:2013-05-19 18:02:11
【问题描述】:

基本上我想要一个链表数组,每个链表都有自己的标题。 这是我的代码:

struct node{
    int location;
    struct node *next;
    struct node *previous;
};

typedef struct ListHeader{
    nodeType *first;
    nodeType *current;
    nodeType *last;
} ListHeader;

struct adjList{
    ListHeader *header;
    int size;
};

struct List{
    adjListType *list;
    int size;
};

ListType newList(int numVerts){
    ListType new = malloc(sizeof(struct List));
    new->list = calloc(numVerts, sizeof(adjListType));
    new->size = numVerts;
    int i;
    for(i = 0; i <= numVerts; i++){
        new->list[i] = newAdjList();
    }
    return new;
}

adjListType newAdjList(void){
    adjListType new = malloc(sizeof(struct adjList));
    new->header = malloc(sizeof(ListHeader));
    new->header->first = NULL;
    new->header->current = NULL;
    new->header->last = NULL;
    new->size = 0; 
    return new;
}

nodeType newNode(int location){
    nodeType new = malloc(sizeof(struct node));
    new->location = location;
    return new;
}

当我尝试使用此代码移动到链表中的下一个节点时,它给了我一个错误 (ListType l, int 位置)

l->list[location]->header->current = l->list[location]->header->current->next; 

这是我得到的错误:

成员引用基类型“nodeType”(又名“struct node*”)不是结构或联合

【问题讨论】:

  • 在我的头文件中,我将 node 定义为 typedef struct node *nodeType;
  • @user2416553 对我来说,那里有很多指针,你可能根本不需要。
  • @user2416553 就“设计”而言,Kraken 的建议非常好。我用你的设计更新了我的答案。

标签: c arrays linked-list nodes


【解决方案1】:

如果你想要链表数组,为什么要使用指针?

struct List{
    adjListType list[10];
    int size;
};

当然,您也可以使用指针,但是您需要向我们展示如何使用calloc 为它分配数组内存?


根据有问题的更新代码..以下是错误修复行...

ListType newList(int numVerts){
    ListType new = malloc(sizeof(struct List));
    new->list = calloc(numVerts, sizeof(struct adjListType));//Here you missed struct
    new->size = numVerts;
    int i;
    for(i = 0; i < numVerts; i++){ // Here <= instead of < for 10 length array is 0 to 9
        new->list[i] = newAdjList();
    }
    return new;
}

此外,您可能希望返回 &new 作为参考,否则您最终会创建不必要的副本...

我要去你的代码,如果我发现其他任何东西,我会更新这个答案。同时,如果你能告诉我们你得到了什么错误,那就太好了?

此外,在您显示的代码中,您将 nextprevcurrent 设置为 NULL,但是您正在更改这些值...否则您将继续获得 NULL POINTER EXCEPTION

【讨论】:

  • 是的,我正在使用 calloc,我已经读取了一个输入以确定数组的大小。是的,我正在使用 Calloc。
  • 我使用指针是因为它们对于我将要创建的未来函数非常有用。
  • 我在 adjListType 前面添加了“struct”,它吐出:'sizeof' 无效应用到不完整类型'struct adjListType'
  • 当我插入/创建节点时,我也在初始化下一个、上一个、第一个、当前和最后一个的值。
  • 如果sizeof(struct List) 工作正常.. 那么sizeof(struct adjListType) 有什么问题?检查拼写错误
【解决方案2】:

创建一个指向struct node 的指针数组。对于链表数组,这应该足够了。

数组的每个元素,即指向struct node 的指针将充当列表的标题,并且可以通过随后从列表中添加/删除元素来维护列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2015-08-16
    • 2014-08-06
    • 2012-09-29
    相关资源
    最近更新 更多