DIGIT-ARC read-only archive · snapshot: July 23, 2026

problem in out put while using pointer in C++

4 posts · originally from https://geek.digit.in/community/threads/problem-in-out-put-while-using-pointer-in-c.145637/

P
priyaranjan Original post #1
Aug 27, 2011 at 1:05 PM
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
nims11 #2
Aug 27, 2011 at 2:46 PM
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).
P
Aug 28, 2011 at 2:34 AM
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.
nims11
nims11 #4
Aug 28, 2011 at 9:57 AM
it is compiler dependent. in mingw, all the output's were garbage.