I'm fairly new to programming and new here, so please be gentle..! I'm trying to dynamically allocate an array of structs (actually an array of pointers to structs) and I'm having a world of trouble.
This is my attempt so far:
el_to_ASIC * block;
el_to_ASIC ** arr_of_ptrs;
block=malloc(num_struct * sizeof(el_to_ASIC));
arr_of_ptrs=malloc(num_struct * sizeof(el_to_ASIC *));
arr_of_ptrs[i]=block+(i * sizeof(el_to_ASIC));
arr_of_ptrs[i]->Mod=i; //insert new block here (see comment below)
#define ARR 1
typedef struct _el_to_ASIC
unsigned int Mod;
unsigned int ASIC;
unsigned int output_num;
unsigned int e_subband;
It does seem to work, but when I run it through valgrind I get lots of invalid write errors. this is part of a larger project, but this code is an 'in vitro' example of the problem I'm having.
I also tried splitting up the memory allocation and assigning to the variables into two seperate blocks (insert:
where I indicate in my comment in the code.) Then I get a segfault caused by an invalid write, and I can't work out why..
I'm sure I must be misunderstanding something---I've read a lot about malloc etc. (oh, and I know I'm not free-ing, that's just to save space in this snippet, I do in the larger program) but can't seem to see where i'm going wrong.
p.s. I can't use C++. Not my choice, so pls don't tell me to!