I have a while
loop that exits when an if(condition){break;}
is met, after an unknown number of iterations. Inside the while
loop, a function is called, that will return an array of variable size at every iteration. I know in python
I could just append the arrays one to each other, and in the end I would have an array of arrays of variable size. What is the right approach to do it in C
?
Here is the relevant part of my code (I know it is not a MWE, many parts are missing, but I hope it is still understandable):
int find_zeros(double *kappa, double *zeros){
// reset the counter "z"
int z = 0;
// do some calculations and compute the zeros
// update the value of z for every zero found
// "zeros" now contains "z" elements
return z;
}
double *foo(){
// allocate memory for the "zeros" array (I know that N>z)
double *zeros = (double *) malloc (sizeof(double) *N);
// variable to count the elements of the "zeros" array
int z;
while (1){
z = find_zeros(kappa, zeros);
// if no zeros where found, exit the while loop
if (z==0){ break; }
// now we know how many zeros we have (z has been updated
// by find_zeros()), so we can reallocate the memory
zeros = (double *) realloc(zeros, sizeof(double) *z);
// append the zeros somewhere (how?!)
// in python I would do: zeros_list.append(zeros)
}
// free the memory for the "zeros" array
free(zeros);
// return all the zeros found
// in python I would do: return zeros_list
}
int main(){
double *zeros_list = what??
// how do I allocate memory of a thing that I don't
// know how big it is going to be?
zeros_list = foo();
}