0

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].

I tried a lot of possibilities, but non of them worked...

char temptask[40];
mon->task=malloc(strlen(temptask)+1);
lili
  • 45
  • 6

3 Answers3

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.

Gopi
  • 19,784
  • 4
  • 24
  • 36
  • i have tried that option but for some reason the compailer screms: "="- cannot convert from 'void *' to 'char *' – lili Jan 28 '15 at 08:36
  • 1
    What compiler are you using that can't convert from `void*` to `char*`? See http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – John Zwinck Jan 28 '15 at 08:49
  • 2
    @JohnZwinck Sounds like a C++ compiler to me. :( – unwind Jan 28 '15 at 08:57
  • 1
    @unwind You should be right. The most acclaimed answer of yours not to cast `malloc()` answers the OP's question :) – Gopi Jan 28 '15 at 08:58
  • @lili: If you're using a C++ compiler you need to cast the result of malloc, like `(char*)malloc(...)`. – John Zwinck Jan 28 '15 at 09:00
  • Better: If you use a C++ compiler, you should program in C++. Use `new`, `delete` etc. If you want to program in C, use a C compiler (resp. tell your compiler to compile in C). – glglgl Jan 28 '15 at 09:18
0

char *task[40]; is an array of 40 pointers. 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). You can't call strlen() on an uninitialized C string, that's undefined behavior (buffer overrun).

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
0

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 = 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];, that means, an array of 40 char *s, then you have to allocate memory for each of them, one by one.

int p = strlen(temptask);
for(i=0;i<40;i++)
{
      mon[j].task[i] = malloc(p+1);
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261