错误:在'struct'之前的预期表达式,在创建链接列表时

时间:2017-10-18 16:58:07

标签: c struct linked-list

我在尝试制作链表时遇到错误。在我尝试malloc()新节点的两行中,错误是“struct'之前的预期表达式”。我看过类似的问题并尝试修复我的代码,但我无法让它工作。任何帮助将非常感谢。

#include <stdio.h>
#include <stdlib.h>

struct List {
    int x;
    struct List *next;
};

int main() {
    struct List* head = (struct List*)malloc(sizof(struct List));
    if (head == NULL) {
        return 1;
    }

    head->x = 1;
    head->next = (struct List*)malloc(sizof(struct List));
    head->next->x = 2;
    head->next->next = NULL;

    struct List* current = head;
    while(current != NULL) {
        printf("%d", current->x);
        current = current->next;
    }
    return 0;
}

1 个答案:

答案 0 :(得分:1)

在这样的陈述中有一个拼写错误

struct List* head = (struct List*)malloc(sizof(struct List));
                                         ^^^^^

必须有

struct List* head = (struct List*)malloc(sizeof(struct List));
                                         ^^^^^^

考虑到根据C标准,没有参数的函数main应声明为

int main( void )

在退出程序之前,您应该为列表释放所有已分配的内存。