AlexS
AlexS

Reputation: 520

Array initialization in C causes Access Violation

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);
}

Upvotes: 2

Views: 133

Answers (1)

Aman
Aman

Reputation: 8985

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.

Upvotes: 14

Related Questions