Hello,
I'm using a function to make a pointer point to some dinamically allocated memory (allocated by the function). The problem is that when the function returns, the pointer doesn't keep the new address.
I don't understand what I'm doing wrong. Here I post a simple example that shows what I mean.
You need to pass the pointers by reference, not value.
The way you are doing it the function receives a copy of the pointer rather than the pointer itself. So you modify the copy and that gets destroyed when the function returns.
By passing a reference you modify the pointer that you passed in rather than a local copy:
To remain compatible with C you would need to pass a pointer to your pointer:
1 2 3 4 5 6 7
void f(int** p) // note pointer to pointer to int
{
int* n = (int*) malloc(sizeof(int));
*p = n; // change what p points to (the pointer you want to modify)
printf("in f(): n = %d, p = %d.\n\n", n, *p);
}
Notice that the p needs to be dereferenced with * to treat it like a pointer compared with simply using p as you did before.
Also, malloc() is good for C but you should really use new for C++.
Thanx Galic, that's a better solution than returning a pointer everytime.
ps: yes I forgot to change the headers. I planned to use C but I don't have a Unix OS anymore and Dev-C++ was reporting its beautiful [build error]. So I switched to C++.
I'm not doing professional things or similar, just studying some algorithm techniques (red-black trees today) so I didn't care a lot about headers. In reality the first Galik's reply was exactly was I was looking for, but I took my C book and could not find such a thing in there so I was wondering if there were a similar approach in C. In the end I solved the Dev-C++ boring problem too.
Sorry for the late reply and thank you again! Today I learned more than I expected!