d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Explanation Needed!
Add Reply New Topic New Poll
Member
Posts: 2,264
Joined: Jul 7 2007
Gold: 26.00
Dec 3 2013 03:35pm
Hey guys i'm doing a sample final for my programming class and I couldn't figure out why the answer to this question is 1 as I thought it would print out 2. If somebody could give me a quick explanation it would be greatly appreciated!

Code

int main() {
int a = 1;
int *x = new int;
*x = a;
a++;
cout << *x;
}
Member
Posts: 9,803
Joined: Jun 28 2005
Gold: 6.67
Dec 3 2013 03:46pm
If this is the exact example from your programming class, you should tell your professor that he's a dumbass for not managing his resources correctly. (not only he uses naked new, but also he fails to free allocated memory).

As to the question, check this out:


Basically, you copy the value of a to memory pointed to by x.
After that you change the value of a, but the value stored in x doesn't change.

Had you pointed x to a (x = &a), then 1 would be printed.
Member
Posts: 2,264
Joined: Jul 7 2007
Gold: 26.00
Dec 3 2013 03:48pm
Quote (KrzaQ2 @ Dec 3 2013 05:46pm)
If this is the exact example from your programming class, you should tell your professor that he's a dumbass for not managing his resources correctly. (not only he uses naked new, but also he fails to free allocated memory).

As to the question, check this out:
http://www.youtube.com/watch?v=UvoHwFvAvQE

Basically, you copy the value of a to memory pointed to by x.
After that you change the value of a, but the value stored in x doesn't change.

Had you pointed x to a (x = &a), then 1 would be printed.


oh wow yea that is so obvious now that I think about it. Thanks a lot buddy I appreciate it!
Member
Posts: 3,383
Joined: Jun 24 2008
Gold: 90.00
Dec 15 2013 09:00pm
Quote (KrzaQ2 @ Dec 3 2013 04:46pm)
If this is the exact example from your programming class, you should tell your professor that he's a dumbass for not managing his resources correctly. (not only he uses naked new, but also he fails to free allocated memory).

As to the question, check this out:
http://www.youtube.com/watch?v=UvoHwFvAvQE

Basically, you copy the value of a to memory pointed to by x.
After that you change the value of a, but the value stored in x doesn't change.

Had you pointed x to a (x = &a), then 1 would be printed.


Makes me think programmers are crazy.
Member
Posts: 9,803
Joined: Jun 28 2005
Gold: 6.67
Dec 16 2013 05:27am
If anything, we're logical to the extreme ;)
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll