can you tell me whats the output here

May 29, 2013 at 6:20pm
int x=9;
int *yptr;
yptr=&x;
yptr+=2;

cout<<*yptr;
system("pause");
}
May 29, 2013 at 6:32pm
The code has undefined behavior. Nobody can say what will be outputed.:)
Last edited on May 29, 2013 at 6:33pm
May 29, 2013 at 6:43pm
It would be whatever value that is stored in the x's address + 2
you have int x = 9
and the pointer *yptr
&x is what obtains the address from x
yptr is obtaining this address as the value

so the in a quick example
yptr is = x's address + 2
so *yptr is now taking the value of this new address and will output it

example:(making up some fake address
yptr=100 + 2
*yptr=value(102)
Last edited on May 29, 2013 at 6:48pm
May 29, 2013 at 6:48pm
@gobiking

It would be whatever value that is stored in the x's address + 2


More precisely it would be said
in the x's address + 2 * sizeof( int )
May 29, 2013 at 6:48pm
Then it would be 11 is that right ??
May 29, 2013 at 6:49pm
yeah i changed it right after i realized the yptr+=2 was not *yptr+=2 XD
May 29, 2013 at 6:51pm
As I said nobody can say what will be outputed. The code has undefined behavior. We do not know whether there is an object of type int at address &x + 2
May 29, 2013 at 6:52pm
is this a homework assignment for you because you can just type in an ide and it will tell you what you will get.
Last edited on May 29, 2013 at 6:53pm
May 29, 2013 at 7:03pm
yaraa wrote:
Then it would be 11 is that right ??
No, it would be random memory.

Note that there is a very huge different between these two lines of code:
1
2
yptr += 2;  //change value in yptr
*yptr += 2; //change value at yptr 
Last edited on May 29, 2013 at 7:03pm
Topic archived. No new replies allowed.