I am trying to figure out why I am getting an error when I assign a value to a structure in an array of structures in heap-allocated memory.
I have the follow C struct:
typedef struct _Point{
int x;
int y;
}Point;
and an array of Point:
typedef Point Sample[];
Now I want allocate an array of Sample in witch any Sample consists of 15 Points and I using the follow code:
Sample *new_positions;
data.old_positions =(Sample*) malloc(sizeof(Point) * 15 * global.nsamples);
When I try to use it with the follow code in order to assign a value, I have an error
data.old_positions[0][0].x=5;
Where is the problem? 🙁
data.old_positions is only single dimension –
Assigns the Zeroith item. You’re better off simulating two dimensions than constructing a 2D array.
(Sample *)malloc(...effectively constructs a single dimensional array with no contents. You’re going to need to malloc the second dimension…That should do it.