【问题标题】:Error: Expected Expression Before 'struct', when making a linked list错误:创建链接列表时,“结构”之前的预期表达式
【发布时间】:2017-10-18 16:58:07
【问题描述】:

我在尝试创建链接列表时不断收到错误消息。在我尝试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;
}

【问题讨论】:

  • 不应该是sizeof而不是sizof吗?
  • sizof() -->> sizeof()
  • 另外,你不需要转换malloc()的返回值。

标签: c struct linked-list


【解决方案1】:

这样的语句有错别字

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

应该有

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

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

int main( void )

并且你应该在退出程序之前释放所有分配给列表的内存。

【讨论】:

  • 是的,没有注意到错字。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
  • 1970-01-01
  • 2014-02-22
  • 1970-01-01
  • 2023-04-11
  • 2014-04-20
相关资源
最近更新 更多