For home-work, I need to define a function that allocate memory to an array of strings (which is into a struct).
The length of each string is given: MAX_WORD_LEN+1 (=10+1)
I have to allocate memory for len number of strings, len is recieved in the input.
Struct with the array of strings definition (given):
struct dict{
int len;
char (*dict0)[MAX_WORD_LEN+1];
char (*dict1)[MAX_WORD_LEN+1];
};
I don't understand the declaration char (*dict0)[MAX_WORD_LEN+1];
- The function declaration is also given:
void createDict(struct dict* myDict);
This is what I wrote, but I'm not sure it works, and I have a difficult time checking it in the compiler. I also wrote it based on post from this and other websites and do not really understand it:
OPTION 1:
void createDict(struct dict* myDict)
{
myDict->(*dict0) = malloc( (myDict->len)*sizeof(char*));
myDict->(*dict1) = (char**) malloc( (myDict->len)*sizeof(char*));
for(int i=0;i<(myDict->len);i++)
{
(myDict->(*dict0)[i]) = (char*)malloc((MAX_WORD_LEN+1)*sizeof(char));
(myDict->(*dict0)[i]) = (char*)malloc((MAX_WORD_LEN+1)*sizeof(char));
}
}
OPTION 2:
(myDict->(*dict0)[MAX_WORD_LEN+1]) = malloc((myDict->len) * sizeof(char*));
(myDict->(*dict1)[MAX_WORD_LEN+1]) = malloc((myDict->len) * sizeof(char*));
Please explain to me...
*dict, you would be correct. As presented, you are not.