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?
1 Answer 1
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])
sideshowbarker
89.2k30 gold badges219 silver badges216 bronze badges
answered Nov 5, 2014 at 11:20
Mohit Jain
30.6k8 gold badges80 silver badges104 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
struct
You can also do
*(*x + k) = k and *(*y + k) = k as an alternative syntax.Brieuc de R
Wonderful! Drives me crazy how long I was looking for a mistake like this... Thank you
lang-c