0

I have this code:
in my judgement it should print 1 and 2, instead it prints 0 and 1
some advice pls... Im using dev c++

#include <iostream>

class A
{
public:
A()
{
arr = new int[2];
}
~A(){ delete [] arr; }

int * arr ;
};


int main() 
{
int * n ; 

{//induced code block
  A aObj;
aObj.arr[0] = 1;
aObj.arr[1] = 2;
n = aObj.arr;

/*
 BTW I assume n now points to the same add of  aObj.arr ... am I wrong??
*/
}

std::cout << "\n" << (*n) << " " << (*n+1);
system("pause");
}
3
Contributors
3
Replies
4
Views
8 Years
Discussion Span
Last Post by VernonDozier
0

The problem is scoping -- object A goes out of scope before the cout statement on line 31. Delete the { and } on lines 20 and 29 and your program will work as you expect it to.

0

good, thanks I should've seen that
the morale is dont let garbage printed on the screen fool you even if it looks extremly similar too what you expect

0

Keep in mind that this line (see red part):

std::cout << "\n" << (*n) << " " << (*n+1);

displays aObj.arr[0] + 1 , not aObj.arr[1] . In your case, they are the same, but if you change line 23 to equal something other than 2, you'll still get 1 2 as output.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.