2

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);
}
AlexS
  • 510
  • 2
  • 7
  • 23

1 Answers1

14

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.
Community
  • 1
  • 1
axiom
  • 8,765
  • 3
  • 36
  • 38
  • Ah yes makes sense when you thibnk of it like that. I didn't know about the precedence! Thanks – AlexS Mar 26 '15 at 18:30