0

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 :)

1

1 Answer 1

5

C uses pass by value. So here:

int getarr(int *dim, double *dubarr)

the function receives dubarr, a pointer to double, passed by value. So, whatever the function assigns to dubarr cannot be seen outside getarr. Note that the implementation of getarr modifies dubarr, but the caller will not see those modifications.

Contrast that with how you handle dim, where you modify *dim. Similarly look at the call to getarr in your code:

getarr(&(data->dim), data->dubarr);

Observe how the two arguments are treated differently. For the first argument you pass the address of a variable, for the second you pass the value of the pointer.

Instead you need:

int getarr(int *dim, double **dubarr)

And then assign to *dubarr like this:

*dubarr = malloc(...);

And call getarr like this:

getarr(&(data->dim), &(data->dubarr));
Sign up to request clarification or add additional context in comments.

1 Comment

Impressive. Very nice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.