741 views
0 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 1 vote
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
Position:
Show:

Related questions

1 1 vote
2 2 answers
831
831 views
radha gogia asked Jul 26, 2018
831 views
For the structure variable x , what is the difference between x and &x ?Also why is &x.val is an error ? Isn't it the address of the structure to which x is pointing to ...
0 0 votes
1 1 answer
1.5k
1.5k views
radha gogia asked Jul 28, 2015
1,471 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...
2 2 votes
2 2 answers
733
733 views
radha gogia asked Sep 3, 2015
733 views
why can't we say that A functionally determines B from the given relation instance when it satisfies the constraints since for unique value of A we have unique value of B...
0 0 votes
1 1 answer
1.4k
1.4k views
radha gogia asked Oct 16, 2018
1,437 views
In the below table why can't we form minterms where the function takes value 0 , say for the first combination why can't we write a'b'c' as one of the minterms ?What's th...