How to change pointer within a function

Hi All,

I try to change to address where a pointer points to within a function.
I don't understand why the following code doesnt work

1
2
3
4
 void changePointer(int* a, int n)
{
   a = new int[n];
}


I want the pointer to point to new allocated memory after function "changePointer" been called

Thank u in advance
There are three methods. The first is to return the new pointer from the function. For example

1
2
3
4
5
6
7
8
9
10
11
12
13
int * changePointer(int* a, int n)
{
   a = new int[n];
   return a;
}

int main()
{
   int n = 10;
   int *p;

   p = changePointer( p, n );
}


The second method is to declare the first parameter as pointer to pointer. For example

1
2
3
4
5
6
7
8
9
10
11
12
void changePointer(int ** a, int n)
{
   *a = new int[n];
}

int main()
{
   int n = 10;
   int *p;

   changePointer( &p, n );
}


And the third method is declare reference to pointer

1
2
3
4
5
6
7
8
9
10
11
12
void changePointer(int * & a, int n)
{
   a = new int[n];
}

int main()
{
   int n = 10;
   int *p;

   changePointer( p, n );
}

closed account (3qX21hU5)
Remember to take care of deleting the pointer when you are done with it. If you don't you will have memory leaks.
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.
@andywestken
Andy

PS In C++ programming you should really be using a std::vector here. Not a pointer to a C-style array


I think you meant std::string instead of std::vector<char>?
thank u for ur answer!

but i still dont understand why my original function fails...
Consider the following code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#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.
Last edited on
I see ...

Thank u all for your help!!
Topic archived. No new replies allowed.