954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

even this simple code?? c'mon c++

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");
}
namehere05
Light Poster
25 posts since Dec 2008
Reputation Points: 11
Solved Threads: 1
 

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.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

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

namehere05
Light Poster
25 posts since Dec 2008
Reputation Points: 11
Solved Threads: 1
 

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.

VernonDozier
Posting Expert
5,527 posts since Jan 2008
Reputation Points: 2,633
Solved Threads: 711
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You