492 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 ?

1 Answer

Best answer
1 votes
1 votes
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

1 votes
1 votes
2 answers
1
0 votes
0 votes
1 answer
2
radha gogia asked Jul 28, 2015
977 views
int * p(void) { int *x; *x=10; return (x); } We create *x, and dereference it before assigning anything to it (x). Most likely, when we are declaring something on the sta...
0 votes
0 votes
2 answers
4
radha gogia asked Aug 2, 2015
843 views
int B [3];int *p = B; // why this is wrong?int (*p)[3] = B; // why this is correct?