in Programming in C
503 views
0 votes
0 votes
int main()  {
    int a;
    struct node *new=(struct node*) malloc(sizeof(struct node));
    //printf("%p",new->link);  
    new->i=1;
    new->link=NULL;  	
    struct node *new1=(struct node*) malloc(sizeof(struct node));
    new1->i=2;
    new1->link=new;  	
    struct node *new2=(struct node*) malloc(sizeof(struct node));
    new2->i=3;
    new2->link=new1;
    struct node *temp;
    temp=new2;
    temp++; 
    printf("%d",temp->i);
    return 0; 
}

I am not getting that why is the op not 2 ,why is it showing some garbage value ?

in Programming in C
503 views

1 Answer

1 vote
1 vote
Best answer
It's because the way you are doing is wrong. You cannot get next value by incrementing like this.

Because Array provide contiguous memory allocation so there we can take advantage of storage organization and get next object value by incrementing.

Since all the node new, new1 and new2 are not contiguously stored in memory so you can not get address of node which is being pointed by incrementing the current node.

Actually the program output is correct, here once you are trying to increment to temp then its pointing to next memory location with an increment of sizeof(struct node) but that is garbage because you have not initialized it.

You can get the value as 2

by changing

temp++

to

temp = temp->link;

you can have a look at this

http://ideone.com/7qf0cV

Related questions