Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning arrays to function pointer arguments in C

Tags:

arrays

c

pointers

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?

like image 692
Brieuc de R Avatar asked Dec 14 '25 06:12

Brieuc de R


1 Answers

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

like image 146
Mohit Jain Avatar answered Dec 16 '25 21:12

Mohit Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!