How to initialize multiple arrays with unknown sizes via a function in C

volkang :

I have a program in C, in which I initialize multiple number of arrays each with a bunch of lines. However, i'd like to avoid that since it increases the length of my main function. For example I have this;

int * pickup_Ind;
double *pickup_Val;
pickup_Ind = (int *) malloc(sizeof(int) * (size1));
pickup_Val = (double *) malloc(sizeof(double) * (size1));

int * lInd;
double *lVal;
lInd = (int *) malloc(sizeof(int) * size2);
lVal = (double *) malloc(sizeof(double) * size2);

int * simul_Ind;
double *simul_Val;
simul_Ind = (int *) malloc(sizeof(int) * (size3));
simul_Val = (double *) malloc(sizeof(double) * (size3));

I know I can reduce the number of lines by for example writing as:

int * pickup_Ind = (int *) malloc(sizeof(int) * (size1));

But still i will need to do this for every array. How to write this in a compact form with a function (which i will store in a header file), and then call this function from main. Not to mention i do not want to declare them as global variables, but to be able to use them in main. I tried the function below.

void initialize_bounds(int *arr1,int size1)
{
arr1= (int *) malloc(sizeof(int) * (size1));
for(int i=0;i<size1;i++)
    arr1[i]=i;  
}

But if i call this function via the following in main, i get error "Varuable test being used without initialized"

int* test;
initialize_bounds(test);

So to sum up, if i could write something like this, my problem is solved:

int *pickup_Ind,*pickup_Val,*lind,*lval;
int size1,size2;
initalize_bounds(pickup_Ind,pickup_Val,size1,size2);
Ctx :

You could write a function

void initialize_bounds(int **ind, double **val, int size) {
    *ind = malloc(sizeof (**ind)*size);
    for (int i = 0; i < size; i++) {
        (*ind)[i] = i;
    }
    *val = malloc(sizeof (**val)*size);
}

and call it like

int * pickup_Ind;
double *pickup_Val;
initialize_bounds(&pickup_Ind, &pickup_Val, size1);

to initialize both arrays in one line. You still have to place one call to it per array-pair, however.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=220220&siteId=1