我有这个结构:
typedef struct
{
char name[3];
int month_num;
int day_num;
int day_size; // amount of days that are field in with tasks.
char *task[40];
}
month; // each month contains a name, its num in the calendar and days.
我需要为其分配内存分配。 我能够为结构本身分配内存:
mon = (month*)malloc(12 * sizeof(month));
但是我很难对 char *task[40] 执行同样的操作。
我尝试了很多可能性,但没有一个起作用......
char temptask[40];
mon->task=malloc(strlen(temptask)+1);
最佳答案
for(i=0;i<40;i++)
{
/* Allocating memory to each pointers and later you write to this location */
mon->task[i] = malloc(size);/* If you have a initialized string then size = strlen(tempTask) + 1 */
}
您拥有的是指针数组,只需访问它们并分别为每个指针分配内存,如上所示。
关于c - 在 C 结构体中的元素上使用 malloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28187579/