c - 使用函数在链表中添加节点

标签 c pointers linked-list runtime-error

我尝试使用CreateRoom函数来添加新节点。
每次添加节点时,我都会编辑旧的“lastRoom.next”并将其设为当前新节点的地址。

然后我将当前新节点的指针作为新的“lastRoom”
我认为这是个好主意,我不需要返回任何东西。我觉得这很好。
然而,它根本不起作用。

我真的不擅长编码,而且我刚刚学习 C。有人可以帮忙吗?

struct Room {
    int number;
    int status;
    int luxury;
    char occupier[20];
    struct Room *next;
};
//I main copy this kind of code from my lecture notes.
//But It's really crappy. This is the only example I can get from the lecture notes
typedef struct Room Room_t;
Room_t *newRoomNode, *ptr, *prev, *temp;
Room_t *firstRoom = NULL, *lastRoom = NULL;

Room_t* CreateRoom(Room_t **first, Room_t **last, int RoomNumber, int type){
    Room_t *new = (Room_t *)malloc(sizeof(Room_t));
    int *temp;
    if (new == NULL)
    {
        printf("\nMemory was not allocated");
        return 0;
    }
    else
    {
//And then I try my way of adding new nodes. 
//I don't really understand the example so I make my own
        if (*last != NULL)
        {
            (**last).next = new;
        }
        new->number = RoomNumber;
        new->luxury = type;
        new->next = NULL;
        *last = new;
        if (*first=NULL){
            *first=new;
        }
    }
    return 0;
}

void main(){
    CreateRoom(&firstRoom, &lastRoom,1,1);
    printf("%d",(*firstRoom).number);
}

最佳答案

if (*first=NULL){
            *first=new;
}

= 是赋值运算符。您应该使用 == 进行比较。

关于c - 使用函数在链表中添加节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29507201/

相关文章:

c - 使用 : as delimiter in shell 提取字符串

c - 请求非结构或 union 中的成员 'x' 和段错误(丢失)

c - 以下程序的输出是什么?如何追踪这样的程序?

要传递给 C 函数的 Objective-C 选择器指针

c++ - 共享指针和原始指针生命周期

c - 使用 C 对链表进行排序

c - 不知道长度的二维全局数组。最佳实践?

c - 我的c代码有什么问题?

c - 以下每个项目都有一个错误(我需要修复它们)

c - Sprite Packing C 应用程序中的 Sprite 对齐