0

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.

1
  • Incidentally, if you're really using C and you have a decent compiler, you don't need to cast the result of your mallocs Commented Nov 3, 2014 at 3:16

1 Answer 1

4

l_bulk_anc_arr is a pointer to an array of 10001 chars. It is not an array.

You still have to allocate memory for it.

struct bulk_data *bulk_counts;
bulk_counts = malloc(sizeof(bulk_data));
bulk_counts->l_bulk_pos_arr = malloc( /*some size*/ );
bulk_counts->l_bulk_anc_arr = malloc(10001);

Now, you can use:

(*bulk_counts->l_bulk_anc_arr)[0] = 'a';
(*bulk_counts->l_bulk_anc_arr)[1000] = '\0';

or

bulk_counts->l_bulk_anc_arr[0][0] = 'a';
bulk_counts->l_bulk_anc_arr[0][1000] = '\0';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.