Pointer dynamic allocation

Hey I am trying to work on some practice problems about dynamic allocation
There is apparently a problem with this function
1
2
3
4
5
6
7
8
9
//What is the problem with this function?
//Dynamically allocates a new integer and sets its value to 10.
//Changes set input ptr to point to that 10.
void ptr_function(int* ptr) 
{
	int *ptr2 = new int;
	*ptr2 = 10;
	ptr = ptr2;
}

If i create a pointer to an int in the main and pass it to this array it seems to work fine. Whats wrong with it? Does dynamic allocation have to be within an array?
Last edited on
What do you mean "it seems to work fine"? Have you tried passing a pointer in, then trying to dereference the pointer after the function executes? That shouldn't work at all.
Oh, so the problem is just that its not passing the pointer back to the main? Like the pointer passed to the function points back to its original address after the function executes?

Sorry the wording of the problem is a little confusing to me
Last edited on
The problem is that ptr is local to ptr_function(). ptr hold the address that you pass to it, sure, but then you assign the address of ptr2. After the function exits ptr no longer exists so the address it holds is leaked since you didn't delete the int ptr2 pointed to. Remember, when you pass a pointer to a function you are passing the address the pointer holds BY VALUE. Therefore, the address passed to the function is a COPIED to ptr which is a separate variable from anything outside the function. In order to get the address out of the function you either need to return it, and assign it to a pointer external to the function, or pass the pointer by reference. Alternatively, you could pass it as a pointer to a pointer, then assign the address of the dynamically created object to the dereferenced pointer to pointer (confusing as hell, I know. :)
Last edited on
how come if i do something like
1
2
3
4
5
6
7
8
9
10
11
12
void f(int* x)
{
	*x = 66;
}
int main()
{
	int* a = new int;
	*a = 3;
	f(a);
	cout << *a << endl;

}

it prints 66? shouldnt it print 3 because x goes away after the function is done?
Last edited on
No, there you are dereferencing the pointer and so modifying what it points to not the pointer itself. Since the object it points to, an int in this case, is external to the function and therefore exists as long as main() exists (even though execution might have passed out of main()) when you modify the pointed to value the modification persists beyond the function.

Remember in your function x contains the address you pass to it, which is the address of the dynamic int you allocated. *x is the object that x points to, or the int itself.

1
2
int x = 0
int* px = &x


In this snippet px holds the address of x. *px is the actual object that px points to.
Last edited on
Topic archived. No new replies allowed.