-
How to malloc (char **)
Hi all,
I am having some trouble with using malloc() and a (char **). Here is a look at my code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Words {
char **wordList;
};
int main() {
int l;
int listCount = 4;
char words[5][25] = {"Season", "Fan", "Car", "Fruit"};
Words *filter;
filter = (Words*) malloc ( sizeof(Words) );
// Write bad words to char array
for (l = 0; l < listCount; l++) {
filter->wordList[l] = (char *) malloc (strlen(words[l]) + 1);
strcpy( filter->wordList[l], words[l] );
}
printf("%s\n", filter->wordList[0]);
for (l = 0; l < listCount; l++) {
free((char *)filter->wordList[l]);
}
free((Words*)filter);
return 0;
}
I'm trying to stay away from using an array of any sort like a char *[], I was just hoping there was a way to allocate memory to a (char **). This is also C, so yes, I would have used new and delete in a split second if it were C++.
Thank you for your time,
- Stack Overflow
-
Something like this?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Words
{
char **wordList;
};
int main(void)
{
int i, listCount = 4;
char words[5][25] = {"Season", "Fan", "Car", "Fruit"};
struct Words filter;
filter.wordList = malloc(listCount * sizeof *filter.wordList);
if ( filter.wordList )
{
for ( i = 0; i < listCount; i++ )
{
filter.wordList[i] = malloc(strlen(words[i]) + 1);
if ( filter.wordList[i] )
{
strcpy( filter.wordList[i], words[i] );
printf("%s\n", filter.wordList[i]);
}
}
for ( i = 0; i < listCount; i++ )
{
free(filter.wordList[i]);
}
free(filter.wordList);
}
return 0;
}
/* my output
Season
Fan
Car
Fruit
*/
>This is also C
Not really.
-
Thanks,
That's exactly what I was looking for :)
- Stack Overflow