I don't understand why the following code doesnt work
In your original code, you are passing the pointer parameter by value. So the value (a) that changePointer sees is a copy of the original value. When you change this copy, you do not change the original value (the one passed to the function)
vlad's assorted solutions get round this problem.
Andy
PS In C++ programming you should really be using a std::vector here. Not a pointer to a C-style array.
#include <iostream>
void f( int x ) { x = 10; }
int main()
{
int a = 0;
std::cout << "Before f(a ) a == " << a << std::endl;
f( a );
std::cout << "After f(a ) a == " << a << std::endl;
}
When you call a function passing an argument by value a new variable that is the function parameter is created and initialized by the argument. In the program I showed this can look the following way
Call f( a ); correcsponds to
int x = a;
x = 10;
// returning the control to main and deleting local; variable x.
So if to consider your original code then it looks the same way
int *p = 0;
int i = 10;
changePointer( p, i );
that corresponds to
int *a = p;
int n = i;
a = new int[n];
// returning the control and deleting a and n.
That is the original variables p and i were not changed. You changed only new variables a and n that are local variables of the function.