3

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?

asked Nov 5, 2014 at 11:18
0

1 Answer 1

7

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

sideshowbarker
89.2k30 gold badges219 silver badges216 bronze badges
answered Nov 5, 2014 at 11:20
Sign up to request clarification or add additional context in comments.

2 Comments

You can also do *(*x + k) = k and *(*y + k) = k as an alternative syntax.
Wonderful! Drives me crazy how long I was looking for a mistake like this... Thank you

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.