problem in out put while using pointer in C++

priyaranjan

Right off the assembly line
Code:
#include<iostream>
using namespace std;

class test
{
public:
    	int* i ;
       test(int k)
	   {
		i=&k;  
	   }

};

int main()
{
	
	test p(2);
    cout<<"for 1st time *(p.i) :"<< *(p.i);
	cout<<"\n";
	cout<<"for 2nd time *(p.i) :"<< *(p.i);
	cout<<"\n";
	cout<<"for 3rd time *(p.i) :"<< *(p.i);
	
   return 0;


}




Hi ,
The above c++ code that i compiled in visual c++,i got the following out put


output

for 1st time*(p.i) :2
for 2nd time *(p.i):20609120
for 3rd time *(p.i) :20609120


The first output is ok,but in 2nd and 3rd the out put is garbage .could any one please explain why this garbage values are coming in 2nd and 3rd?
 

nims11

BIOS Terminator
that's because you are passing a constant value to the constructor which is passed by value. when you pass 2 to the constructor, it is copied to a variable called k whose scope is local to the test() constructor. so when the constructor finishes its job, all left in the memory address of k (which i is pointing to) is some garbage value.

also, if you try to achieve the objective by using a pointer or references, passing a constant value like 2 will cause errors and you will have to store the value to some variable and then pass that variable (address).
 
OP
P

priyaranjan

Right off the assembly line
Hello nims11,

Thank you very much for your reply.Still i have a doubt ,the thing is that when i have printed 1st time the constructor has finished its work ,so the out put at the first print statement should give the garbage out put ,but instead of that it is showing 2 which i passed as argument to the constructor.
 
Top Bottom