passing a argument of function as an address

Feb 19, 2013 at 9:19am
I try to understand the output of the folowing code ( 10 ), but it looks too complicate .I guess it is connected with dinamic memory alloc. but i'm not shure.

void afunction(int *x)
{
x=new int;
*x=12;
}
int main()
{
int v=10;
afunction(&v);
cout<<v;
}
Feb 19, 2013 at 11:07am
I think this could be something to do with stack vs heap. When you use the new keyword, you're allocating memory on the heap. The previous instance of this object, in your case v is allocated on the stack.

When you use new, you're no longer using the same address as what you've passed in. Therefore, the instance in main is unchanged.

One other thing that should be noted is that you're not freeing the dynamically allocated memory in your function. You have a memory leak.

Run this example...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

void MyFunction( int *x )
{
  std::cout << "Address of x: " << x << std::endl;
  x = new int;
  std::cout << "New address of x: " << x << std::endl;
  delete x;
}

int main( int argc, char* argv[] )
{
  int y = 10;
  std::cout << "Address of y: " << &y << std::endl;
  MyFunction( &y );
  std::cout << y << std::endl;
}


I'm sure this is just for the sake of example, but I can't think of a good time when you'd ever need to do this.
Last edited on Feb 19, 2013 at 11:31am
Feb 26, 2013 at 6:34am
Thank's a lot
Topic archived. No new replies allowed.