Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array initialization in C causes Access Violation

Tags:

c

Could someone please put me out of my misery and tell me why I get an Access Violation when initializing the array with ones?

#include <stdio.h>

void initData(float **data, size_t N)
{
    int i;
    *data = (float*)malloc( N * sizeof(float) );

    for (i=0; i<N; i++)
    {
        *data[i] = 1.0;
    }
}

void main()
{
    float *data;
    initData(&data,8);
}
like image 797
AlexS Avatar asked Apr 13 '26 02:04

AlexS


1 Answers

Dereference (*) has a lower precedence than the square bracket operator []. What you write is thus effectively translated to:

*(data[i]) = 1.0;

whose failure shouldn't surprise anyone.

Change it to:

(*data)[i] = 1.0;

and it won't break.


Include stdlib.h to get rid of the warning.
like image 53
axiom Avatar answered Apr 15 '26 16:04

axiom



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!