我不知道为什么我下面的结构没有被设置

I don't know why my structs below are not being set

goodsubject-lm:chap6 varunvb$ cat linkedlists.c

#include <stdio.h>

typedef struct island {
  char *name;
  char *opens;
  char *closes;
  struct island *next;
} island;

island amity = {"Amity", "09:00", "17:00", NULL};
island craggy = {"Craggy", "09:00", "18:00", NULL};
island isla_nublar = {"Shutter", "09:00", "19:00", NULL};
island skull = {"Skull", "09:00", "20:00", NULL};
island shutter = {"Shutter", "09:00", ":21:00", NULL};
amity.next = &craggy;
craggy.next = &isla_nublar;
isla_nublar.next = &skull;
skull.next = &shutter;

void display (island *start) {

  island *i = start;

  for (; i != NULL; i == i->next) {
     printf ("Name: %s\nOpens: %s\ncloses: %s\n", i->name, i->opens, i->closes);
     }
}

int main ()
{
 display (&amity);
 display (&craggy);
 display (&isla_nublar);
 display (&skull);
 return 0;
}

我得到的错误如下。

linkedlists.c:15:1: error: unknown type name 'amity'
amity.next = &craggy;
^
linkedlists.c:15:6: error: expected identifier or '('
amity.next = &craggy;
     ^
linkedlists.c:16:1: error: unknown type name 'craggy'
craggy.next = &isla_nublar;
^
linkedlists.c:16:7: error: expected identifier or '('
craggy.next = &isla_nublar;
      ^
linkedlists.c:17:1: error: unknown type name 'isla_nublar'
isla_nublar.next = &skull;
^
linkedlists.c:17:12: error: expected identifier or '('
isla_nublar.next = &skull;
           ^
linkedlists.c:18:1: error: unknown type name 'skull'
skull.next = &shutter;
^
linkedlists.c:18:6: error: expected identifier or '('
skull.next = &shutter;
     ^
linkedlists.c:24:23: warning: equality comparison result unused [-Wunused-comparison]
  for (; i != NULL; i == i->next) {
                    ~~^~~~~~~~~~
linkedlists.c:24:23: note: use '=' to turn this equality comparison into an assignment
  for (; i != NULL; i == i->next) {
                      ^~
                      =
1 warning and 8 errors generated.

for (; i != NULL; i == i->next) {

我想你的意思是 i = i->next。您的循环要么是无限的,要么永远不会 运行.

对于您的错误,您不应使用全局变量,而应在您的代码中创建和 link 您的元素。正如 M Oehm 评论的那样,至少将你的 x.next = &y 语句移到你的主语句中。

你可以有一个孤岛工厂函数,它分配一个指向 island 的指针并填充它,然后 returns 它。

例如:

island *add_island(island *begin, char *name, char *opens, char *closes)
{
  island *new = malloc(sizeof(*new));

  if (new == NULL)
  {
    printf("Malloc error in add_island");
    return NULL;
  }
  new->name = name;
  new->opens = opens;
  new->closes = closes;
  new->next = begin;

  return new;
}

int main(void)
{
  island *list = add_island(NULL, "last island", "12:00", "02:00");
  list = add_island(list, "first island", "20:00", "10:00");
  display(list);
}

add_island 作为对给定列表的推送。