0

I want to define multiple array pointers in my main, and then pass these pointers into a function to allocate memory for them. The thing is that the size of the array is not known before entering somefunction. I am not sure how to do this or if there is a better way to do this, but I tried with this code, which did not work.

void somefunction(int *arr1,int *arr2){
    int M = 3;
    int N = 2;
    arr1 = (int*)malloc(M*sizeof(int));
    arr2 = (int*)malloc(N*sizeof(int));
}

int main(){
    int* array_1;
    int* array_2;
    somefunction(array_1,array_2);
    //Here I want array_1 to be of size M and array_2 of size N
}
Stumpp
  • 279
  • 4
  • 7
  • 16
  • When do you definitely know the size of the Arrays ? – Pierre Mar 18 '19 at 12:50
  • After doing some actions in the start of somefunction. Simplified by setting M=3 and N=2. So after M and N i set, the size is known – Stumpp Mar 18 '19 at 13:03
  • Define `somefunction` as `void somefunction(int **arr1,int **arr2)` and call it from main with `somefunction(&array_1,&array_2)`. Allocate with `*arr1 = (int*)malloc(M*sizeof(int));` – i486 Mar 18 '19 at 14:54
  • Will it be safe to set a `temporary_array = (int*)malloc(M*sizeof(int));` inside `void somefunction(int **arr1,int **arr2)` and then set `*arr1 = temporary_array`? Or will `temporary_array` be removed from memory after `somefunction` has been executed? – Stumpp Mar 18 '19 at 23:21

0 Answers0