Reputation: 18875
I am not quite clear on how to allocate memory to a struct pointer that contains a dynamic array field. for example, I have the following struct:
typedef struct log_file {
char *name;
int updatesize;
int numupdates;
int *users; /* dynamic array of integers */
} log_data;
When I created a pointer of log_data
using: log_data *log_ptr = malloc(sizeof(log_data));
How do I allocate enough memory for the dynamic array users
in the struct?
Upvotes: 0
Views: 97
Reputation: 30136
How about:
log_ptr->users = malloc(sizeof(int)*numOfUsers);
Or if you want to keep it independent of the type of *users
:
log_ptr->users = malloc(sizeof(*log_ptr->users)*numOfUsers);
Upvotes: 1