I'm declaring pointers before my function call and want to get arrays when the function is executed. I followed the question answered here to obtain the following code
double *x;
double *y;
myfunction(1.0,&x,&y);
printf("x[0] = %1.1f\n",x[0] );
Where myfunction is
void myfunction(double data, double **x, double **y){
/* Some code */
int calculated_size = 10;
*x = malloc(calculated_size*sizeof(double));
*y = malloc(calculated_size*sizeof(double));
int k;
for (k = 0;k < calculated_size; k++)
{
*x[k] = k ;
*y[k] = k ;
}
}
Which gives me a segmentation fault as soon as it tries to assign
*x[k] = k;
Could someone indicate the exact way I should be doing this?
Replace *x[k] = k ; with (*x)[k] = k ; or better use as shown below
int *xa = *x;
xa[k] = k ;
[] binds tighter than * in C Operator precedence table causing the fault.
You expect : (*x)[k]
But you get: *(x[k])
Live example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With