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

标签 c struct malloc

我有这个结构:

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/

相关文章:

c - 关于 C 中 calloc 和 free 函数的问题

c - gdb 在使用 math.h 函数时给出奇怪的输出

c - pgcc,C - 循环未并行化 : may not be beneficial

c - 我的c程序出错

c - 为什么这段使用 qsort 函数的代码在 C 中不起作用?

C memcpy 导致段错误

C:在函数原型(prototype)或结构声明中使用#define 值时遇到问题

c++ - uint12 结构中的字节顺序

c - 什么时候应该 typedef struct 与 pointer to struct?

c - 是否可以 free() 函数返回的指针?