0

I am new bee to C. I am currently writing linked list in C. When compiling, it keeps complaining about "assignment from incompatible pointer type". My code is like this:

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

struct snode{
  struct snode *next;
  int val;
};

struct slist{
  struct snode *head;
  struct snode *tail;
  int len;
};

struct slist *mylist;

void slist_insert(int v){
  struct snode *newnode;
  newnode = (struct snode*)malloc(sizeof(struct snode));
  newnode -> val = v;
  newnode -> next = NULL;


  if(mylist->head  = NULL){
    mylist->head  = malloc (sizeof(struct snode));
    mylist->tail = (struct snode*)malloc (sizeof(struct snode));
    mylist->head = newnode;
    mylist->tail = newnode;
    
  };

  else{
    mylist -> tail -> next = (struct snode*)malloc (sizeof(struct snode));
    mylist -> tail -> next = newnode;
  };
   mylist -> len +=1;  
};


main(){
    slist_insert(1);
    slist_insert(2);
    slist_insert(3);
    slist_insert(4);
    slist_insert(5);

    struct snode *temp;
    temp = (struct snode*)malloc(sizeof(struct snode));
    temp = mylist-> head;
    while(temp -> next != NULL){
      printf("%d\n", temp -> val);
      temp  = temp -> next;
    };
  };
    

Here is the modified one. I am using linux terminal to run this program. The compiler I am using is gcc -std=gnu99

UPDATE

slist.c: In function â:
slist.c:32: error: â without a previous â
slist.c: At top level:
slist.c:40: warning: return type defaults to â
4

2 回答 2

4
于 2013-09-01T20:55:22.073 回答
2

next是一个指向 int 的指针,而你希望它是一个指向 struct snode 的指针,我假设。此外,我假设你mylist的应该是一个 slist 而不是指向 slist 的指针。正如评论中所指出的那样,该 mylist 的成员不一定被初始化(依赖于实现。使用您使用mylist指针的模式,您需要首先 malloc(和初始化)那个人......

于 2013-09-01T20:52:41.810 回答