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?

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

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

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.