pointer query ...

What is wrong with this program,

int x,*p;

x = 10;

*p = x;

cout << p << " " << &x;

This works, came across in a book saying it is danger to use this fashion.But I could not get it why ?..any idea...also p and &x displays different address..(tried it on cygwin)
You should make p pointing somewhere before setting the value pointed by it to x.
If you want p to point to the location of x you should use p = &x;
it shouldn't work.

'p' is a pointer, and you're not telling it to point to anything before you assign what it points to a value.

 
*p = x;


at that line of code... p hasn't been initialized to point to anything, so it points to nothing (garbage). By doing this line, you're writing 'x' to some random area in addressing space which might cause a program crash or dreaded memory corruption (these bugs are so hard to trace).

If you want to make p point to x... then you want this:

 
p = &x;


in which case, when you print them like you were with that cout, they will be the same.

edit: Bazzy is too quick =o
Last edited on
Thanks..
Topic archived. No new replies allowed.