使用数组创建单链表时的警告 [英] Warnings when creating a singly linked list with arrays

查看:39
本文介绍了使用数组创建单链表时的警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>

typedef struct
{
  int data;
  struct node *next;
}node;

void print(node *head)
{
  node *tmp = head;
  while (tmp)
  {
    printf ("%d ", tmp->data);
    tmp = tmp->next;
  }
}

int main()
{
  node arr[5] = {
                  {1, &arr[1]},
                  {2, &arr[2]},
                  {3, &arr[3]},
                  {4, &arr[4]},
                  {5, NULL}
                };

  print(arr);
  return 0;
}

为什么在使用 gcc -Wall 进行编译时会收到这些警告?(即使没有 -Wall,gcc 也会产生相同的警告)

Why do i get these warnings while compiling with gcc -Wall ? (even without -Wall, gcc produces the same warnings)

list.c: In function ‘print’:
list.c:15:7: warning: assignment from incompatible pointer type [enabled by default]
list.c: In function ‘main’:
list.c:22:18: warning: initialization from incompatible pointer type [enabled by     default]
list.c:22:18: warning: (near initialization for ‘arr[0].next’) [enabled by default]
list.c:23:18: warning: initialization from incompatible pointer type [enabled by default]
list.c:23:18: warning: (near initialization for ‘arr[1].next’) [enabled by default]
list.c:24:18: warning: initialization from incompatible pointer type [enabled by default]
list.c:24:18: warning: (near initialization for ‘arr[2].next’) [enabled by default]
list.c:25:18: warning: initialization from incompatible pointer type [enabled by default]
list.c:25:18: warning: (near initialization for ‘arr[3].next’) [enabled by default]

推荐答案

您正在尝试在 node 的定义中使用 struct node 因此编译器不会知道你的意思是他们是同一件事.尝试先声明结构体:

You are trying to use struct node inside the definition of node so therefore the compiler doesn't know you mean them to be the same thing. Try forward declaring the struct first:

struct node;
struct node
{
  int data;
  struct node *next;
};

这篇关于使用数组创建单链表时的警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆