[英]Using malloc on a elemnt in struct in C
I have this struct: 我有这个结构:
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.
and I need to assign memory allocation for it. 我需要为其分配内存分配。 I was able to assign the memory for the struct itself:
我能够为结构本身分配内存:
mon = (month*)malloc(12 * sizeof(month));
But I am having trouble to do it the same for the char *task[40]. 但是对于char * task [40],我很难做到这一点。
I tried a lot of possibilities, but non of them worked... 我尝试了很多可能性,但是没有一种可行。
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 */
}
What you have is array of pointers and just access them and allocate memory to each of the pointers individually as shown above. 您所拥有的是指针数组,只需访问它们并分别为每个指针分配内存即可,如上所示。
char *task[40];
is an array of 40 pointers. 是40个指针的数组。 You probably want a single array of 40 characters, in which case no need to malloc it separately, or else a single pointer in which case you can
malloc(40)
. 您可能想要一个由40个字符组成的数组,在这种情况下,无需单独对其进行malloc分配;否则,您可以使用一个
malloc(40)
指针malloc(40)
。 You can't call strlen()
on an uninitialized C string, that's undefined behavior (buffer overrun). 您不能在未初始化的C字符串上调用
strlen()
,这是未定义的行为(缓冲区溢出)。
I think, what you need is 我认为,您需要的是
char *task;
and then allocate memory as 然后分配内存为
mon[j].task=malloc(sizeof(temptask));
Next, as you've allocated memory to mon
as 接下来,因为您已经为
mon
分配了内存,所以
mon = malloc(12 * sizeof(month));
the access should be made as 访问应作为
mon[j].task // j being the index, running from 0 to 11
Otherwise, if you really have a char *task[40];
否则,如果您确实有一个
char *task[40];
, that means, an array of 40
char *
s, then you have to allocate memory for each of them , one by one. ,也就是说,一个
40
char *
s的数组,那么您必须为它们每个分配内存,一个接一个。
int p = strlen(temptask);
for(i=0;i<40;i++)
{
mon[j].task[i] = malloc(p+1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.