I have a struct with a pointer component. The pointer will point to an array whose size will be determined after the struct is declared. I will need to malloc memory and then assign it to the pointer. Somehow passing this pointer through function calls causes problems. Here is a simple example which recreates my error:
#include <stdlib.h>
#include <stdio.h>
typedef struct mystruct mystruct;
struct mystruct{
int dim;
double *dubarr;
double dub;
};
int getarr(int *dim, double *dubarr){
*dim = 2; /* The value of dim is not known until this function is called */
dubarr = malloc(*dim * sizeof(double));
double test;
int i;
for(i=0;i<*dim;i++)
{
dubarr[i] = (i+1)*7.0;
test = dubarr[i];
printf("dubarr[%i] = %.15e\n", i, test);
}
return 1;}
int initmystruct(mystruct *data){
getarr(&(data->dim),data->dubarr);
data->dub = (data->dim)*((data->dubarr)[0]);
return 1;}
int main(void){
mystruct data;
initmystruct(&data);
double test;
int i;
for(i=0;i<data.dim;i++)
{
test = (data.dubarr)[i];
printf("dubarr[%i] = %.15e\n", i, test);
}
/* I would do "free(data.dubarr);" here but it causes a crash */
return 1;}
The code compiles with no warnings but the components of data.dubarr do not maintain their values through the function calls. Here is the output:
dubarr[0] = 7.000000000000000e+00
dubarr[1] = 1.400000000000000e+01
dubarr[0] = 2.002400628035951e+176
dubarr[1] = 2.186218092030684e-154
Please point out all my mistakes :)