I need to pass by reference sub-arrays which are part of a dynamically allocated 2D array. I have tried the following approach, which doesn’t seem to work. Any ideas if it is possible?
void set1(int *a){
a = malloc(2*sizeof(int));
a[0] = 5;
a[1] = 6;
}
void set2(int *a){
a = malloc(2*sizeof(int));
a[0] = 7;
a[1] = 8;
}
int main(){
int **x = malloc(2*sizeof(int*));
set1(x[0]);
set2(x[1]);
return 0;
}
You need to pass the address of your sub-arrays, like in this example:
Whenever you have a function that needs to modify something in the caller’s scope, you need a dereference in the function (like our
*a) and an address-of in the caller (like&x[0]).(Your code, by contrast, assigns the pointer to allocated memory to a local variable (namely
myArray), which is lost when the function returns. And the memory is lost along with it.)