0

So my understanding is that if I have a function with a pointer as parameter and I change the value of it in the function and want that change also to occure outside the function I don't have to return the pointer. For example:

void fubar(char * a)
{
  *a = 5;
}

In this case after calling the function the pointer I used should have the value 5 because the address is still the same right?

But lets say you change the memory dynamically in a function:

void newMem(char * b)
{
  b = (char*) realloc((void*) b, 10 * sizeof(char))
  //etc...
} 

Couldn't it be, that because the memory at the previous location is not sufficient, the pointer will point to some other address after realloc() making this function dangerous. It works just fine in the programm I wrote but I fear it could have a bad outcome as soon the just mentioned case will occure.

So would it be better to do it with a return value like this:

char * newMem(char * b)
{
  b = (char*) realloc((void*) b, 10 * sizeof(char))
  //etc ....
  return b;
} 
notAuser
  • 31
  • 3
  • You're not changing the value of the pointer, you're changing the value of whatever the pointer points to. – Barmar Sep 08 '21 at 19:57
  • Yes @Barmar but if I want to do other stuff with the pointer after returning from the function and realloc() asigned a new address isn't it nessecarry to return the (possibly new) pointer. I mean realloc() does that basically, doesn't it? – notAuser Sep 08 '21 at 20:21
  • Using the return value is one way to do it. – Barmar Sep 08 '21 at 20:23
  • If you are changing the pointer itself you need to either return the new pointer `return b` or pass a pointer to the pointer `char **b; *b = realloc...` – stark Sep 08 '21 at 21:30

0 Answers0