5
  struct node{
        int data;
        struct node *next;
    };
main(){
    struct node a,b,c,d;
    struct node *s=&a;

    a={10,&b};
    b={10,&c};
    c={10,&d};
    d={10,NULL};


    do{
        printf("%d %d",(*s).data,(*s).next);

        s=*s.next;
    }while(*s.next!=NULL);

}

It is showing error at a={10,&b};Expression syntex error.please help.. thankzz in advance

Rohit Goel
  • 53
  • 1
  • 3
  • 1
    Take a look at http://stackoverflow.com/questions/330793/how-to-initialize-a-struct-in-ansi-c for other great answers. – Eric Fortin Jan 29 '15 at 16:21
  • The language provides the `->` operator so that you can say `s->next` rather than `(*s).next`. – AAT Jan 29 '15 at 17:13

2 Answers2

6

Initialization of a struct variable using only bracket enclosed list is allowed at definition time. use

struct node a={10,&b};

Otherwise, you've to use a compound literal [on and above c99]

a=(struct node){10,&b};
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
5

Initialize the variable immediately:

struct node a={10,NULL};

And then assign the address:

a.next = &b;

Or use a compound literal:

a=( struct node ){10,&b};  //must be using at least C99
reader
  • 496
  • 2
  • 15
  • why we are type casting at the time of initialiation in a=(struct node){10,&b}.please explain in detail...thankzzz – Rohit Goel Jan 29 '15 at 16:23
  • @RohitGoel This is an assignment, a is already initialized. That is a compound literal, and that is the selected syntax to use it. – reader Jan 29 '15 at 16:24
  • @RohitGoel your query regarding the _cast_ is well explained in the link provided in my asnwer. Please check that. – Sourav Ghosh Jan 29 '15 at 16:32