I have some code in a couple of different functions that looks something like this:
void someFunction (int *data) {
data = (int *) malloc (sizeof (data));
}
void useData (int *data) {
printf ("%p", data);
}
int main () {
int *data = NULL;
someFunction (data);
useData (data);
return 0;
}
someFunction ()
and useData ()
are defined in separate modules (*.c files).
The problem is that, while malloc works fine, and the allocated memory is usable in someFunction
, the same memory is not available once the function has returned.
An example run of the program can be seen here, with output showing the various memory addresses.
Can someone please explain to me what I am doing wrong here, and how I can get this code to work?
EDIT: So it seems like I need to use double pointers to do this - how would I go about doing the same thing when I actually need to use double pointers? So e.g. data is
int **data = NULL; //used for 2D array
Do I then need to use triple pointers in function calls?