Reputation: 2821
typedef struct {
char name [25] ;
char breed [25] ;
int age ;
struct animal *next ;
} animal ;
animal *ptr1 , *ptr2 , *prior ;
ptr1 = (animal*)malloc( sizeof (animal) ) ;
strcpy ( (*ptr1).name , "General" ) ;
strcpy ( (*ptr1).breed , "Foreign breed" ) ;
(*ptr1).age = 8 ;
(*ptr1).next = NULL ;
prior =ptr1 ;
printf ("%s\n" , (*prior).name ) ;
printf ("%s\n" , (*prior).breed ) ;
printf ("%d\n" , (*prior).age ) ;
printf ("%p\n" , (*prior).next ) ;
free (ptr1) ;
ptr1 = (animal*)malloc( sizeof (animal) ) ;
strcpy ( (*ptr1).name , "General 1" ) ;
strcpy ( (*ptr1).breed , "Abroad breed" ) ;
(*ptr1).age = 24 ;
(*ptr1).next = NULL ;
(*prior).next = ptr1 ;
Here is the code to draw a linked list. The whole code when executes shows an error in the last line:
In function ‘main’: warning: assignment from incompatible pointer type [enabled by default]
Upvotes: 1
Views: 1122
Reputation: 51
That is actually a warning, not an error. I don't get why are you using (*s).m instead of s->m. It is simpler and more natural. I don't see function main in your code and the line where you get the error, I suppose all your code except the struct declaration is the function main. Try declaring your structure like this (you may also need to add a "typedef struct animal", depending on your compiler): struct animal { ... animal *next; };
Upvotes: 0
Reputation: 78903
The "tag" name space (the name after the struct
) and the identifier name space (the one you declare with typedef
, eg.) are distinct in C.
The easiest, I find, is to always forward declare the struct
tag and the typedef
in one go:
typedef struct animal animal;
From then on you could easily use the typedef
name even inside the declaration of the struct
:
struct animal {
....
animal* next;
};
Upvotes: 0
Reputation: 145829
Change your declaration to:
typedef struct animal {
char name [25] ;
char breed [25] ;
int age;
struct animal *next;
} animal;
The structure tag animal
has been added to the declaration.
You now have the type animal
an alias for struct animal
.
Upvotes: 1
Reputation: 170055
change your structue definition to this
typdef struct Animal_
{
char name [25];
char breed [25];
int age;
struct Animal_* next;
} Animal;
Without Animal_
the struct is an anonymous struct, and cannot have a pointer to it.
Upvotes: 1
Reputation: 16718
animal
is the name of the typedef, not the struct. Try this instead:
typedef struct _animal {
char name [25];
char breed [25];
int age;
struct _animal *next;
} animal;
Upvotes: 0