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 = newint;
*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?
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. :)
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.
int x = 0
int* px = &x
In this snippet px holds the address of x. *px is the actual object that px points to.