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");
}

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.

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.