Tuesday, July 14, 2009

Pointers in C++?

For instance, in C++:





int *x;


int *y = new int;


*y=16;


x=y;


delete y;


cout%26lt;%26lt;x%26lt;%26lt;endl;





what will be printed out (nothing or 16)? and why? thanks a lot

Pointers in C++?
Asuming that the cout line is cout %26lt;%26lt; *x %26lt;%26lt; endl:


======================================


The right answer to this question is: undefined. If the particluar memory space still contains 16, it may print 16. But if any other program has now snacthed it and used it for some other purpose, it may be that value. It may be garbage, it may crash, it may punch you on the nose with a hand coming out of the monitor.





The right advice for people who try such things: use C++ the right way. Respect the flexibility that pointers allow you to have. Do not try to access memory that you have not been assigned or you have deleted. What you are trying to do is interacting with a dead person. The ghost might get you!





And yes, I forgot to mention that some compilers do set the value to zero, as one of the answers above states it will be zero. That answer is strictly compiler specific. And such a compiler is too gentlemanly I would say. You should try to write code in such a way that most if not all good compilers run it smoothly.
Reply:0 is printed due to null pointer assignment
Reply:The answer is 0





If you comment out the line


delete y;





then the answer is 16.
Reply:The correct answer is it's undefined, because you're accessing memory that's been deallocated.
Reply:It will print out the memory location of y because you assigned the y to int x, but y is empty.
Reply:it wont print anything,


the results will pretty much just be nothing,


you should download dev-c++
Reply:I compiled your code and ran it and I got an outcome of: 0x32460





I'm not sure why this is because I'm new to C++ (and programming in general).


No comments:

Post a Comment