gpt4 book ai didi

c - 在 C 结构体中的元素上使用 malloc

转载 作者:行者123 更新时间:2023-11-30 15:24:52 25 4
gpt4 key购买 nike

我有这个结构:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com