Can any one tell me why the following code output 10 instead of 12:
#include <iostream>
using namespace std;
void afunction(int *x)
{
x=new int;
*x=12;
}
void main()
{
int v = 10;
afunction(&v);
cout<<v;
}
In my opinion,the address of v is passed to afunction as a parameter,and the value of the variable pointed by it surely is modified.WHY AM I WRONG???
man, in the function afunction(int *x) what happens is, you pass the reference to x, after, FIRST you reserve an int in the heap, and then AFTER, the x is equal to pointer returned by new, which means than the old reference that you passed by parameter is no longer the reference pointed by x. Then you say that x is equal to 12 but it was nothing to do with the v variable.
The correct it's just this:
C style:
1 2 3 4
void afunction(int *x)
{
x = 12;
}
C++ style (preferable):
1 2 3 4 5
void afunction(int& x)
{
x = 12;
}
Note: In C++ style you dont need to pass the reference of v, just v.
If you wish to use afunction() to change the value of v in main(), you must pass v's address, either explicitly or using a reference. You do the former. In afunction() x points at v. To change v using x, you must dereference x, as you do in the line *x=12;. The line x=newint; is the problem. It changes the value of x so that it no longer points at v. Dereferencing it after this is done sets the value of a new int, created on the heap, to 12. Get rid of this line and your code will output 12.
If this is not clear to you, I'd recommend writing down the variables and their values on a sheet of paper and walking through the code, adjusting the variable's values as they change.
As outsid3r stated, in C++ references are available and are nice because the syntax is cleaner. Replace your afunction() with his, in main() change the line afunction(&v); to afunction(v); and your code will output 12.
Incidentally, because the value of x (the address of the int created on the heap) is lost when afunction() exits, your code has a memory leak.