I am trying to use malloc to allocate memory for a struct containing a char array and an int array. I will be populating these two arrays with information from a file whose length I will not know in advance.
typedef struct bulk_data{
int *l_bulk_pos_arr;
char (*l_bulk_anc_arr)[10001];
}bulk_data;
I am still learning memory allocation, but what I imagine here is that since the size of each char array element is fixed, I shouldn't have to loop through that array to allocate memory. At this point I now know the number of array elements I need (n_rows). I have tried the following (obviously not all at the same time):
struct bulk_data *bulk_counts;
bulk_counts = malloc(sizeof(bulk_data)); // 1st attempt
bulk_counts = (bulk_data *)malloc(sizeof(bulk_data)); // 2nd
bulk_counts = malloc(sizeof(bulk_data) * n_rows); // 3rd
bulk_counts = (bulk_data *)malloc(sizeof(bulk_data) * n_rows); // 4th
No errors at compile time, but it appears that the above listed attempts aren't allocating the space properly:
(gdb) p bulk_counts->l_bulk_anc_arr
$1 = (char (*)[10001]) 0x0
(gdb) p bulk_counts->l_bulk_anc_arr[0]
Cannot access memory at address 0x0
(gdb) p bulk_data->l_bulk_pos_arr
$2 = (int *) 0x0
(gdb) p bulk_data->l_bulk_pos_arr[0]
Cannot access memory at address 0x0
I would like to know how I can allocate memory for this stated case, but also in the case when you don't know the number of chars in each char array element.
mallocs