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));
当我使用以下命令创建log_data指针时:log_data * log_ptr = malloc(sizeof(log_data));
How do I allocate enough memory for the dynamic array users
in the struct?
如何为结构中的动态数组用户分配足够的内存?
1 个解决方案
#1
1
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);
#1
1
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);