frank zhu <[EMAIL PROTECTED]> wrote:
>
> Hi,
> I've coded a program to find the nth node from the end
> of the linked list.
> It works and get me the right result, but I am puzzled
> as why I get the compiler warnings at the following line,
> p1 = p1->next;
> findnthnode.c:28: warning: assignment from incompatible
> pointer type
<snip>
> #include <stdio.h>
> // algorithm : use two pointers and they're n-1 nodes
> apart. when first
> reach the end, 2nd one reaches nth node.
>
> typedef struct {
> struct node* next;
> int data;
> }node;
Here you declare an anonymous struct (i.e. a struct with
no tag name) containing a member of type struct node; and
you also create an alias for the anonymous struct called
node. Neither the anonymous struct, or its alias, has
the type struct node.
You probably meant...
typedef struct node { /* note the tag */
struct node* next;
int data;
} node;
> node* findnthnode(node *head, int n)
> {
> node *p1;
<snip>
> p1 = p1->next;
The 'next' member of the anonymous struct is a pointer
to a struct node, not a pointer to the anonymous struct.
Indeed, you never actually declare what a struct node
is.
C allows pointers to incomplete types.
The assignment is a constraint violation and conforming
compilers are required to issue a diagnostic. However,
you appear to have your 'buzz' level so low that it's
not reported as an error.
Try p1 = p1->next->next and see how far your compiler
gets!
This is one of the reasons why many C programmers won't
do the typedef. Instead they simply use struct node
throughout.
--
Peter