I'm learning how to use pointers in C (with malloc and free), and I'm having some troubles with this exercise. I just want to make an array of pointers, where I want to save the direction of every word. Then I want to do a free() for a specific word, but this free makes my program to crash.
int main
{
printf("Introduce how many words do you want. \n");
scanf("%d", &numWords);
getchar();
char ***array = (char***)malloc(sizeof(char**) * numWords);
if (array == nullptr)
{
exit(1);
}
for (int i = 0; i < numWords; i++) array[i] = (char**)malloc(sizeof(char*)) ;
for (int i = 0; i < numWords; i++)
{
printf("Enter your word number %d: \n", i + 1);
scanf("%s", &(array[i]));
getchar();
}
for (int i = 0; i < numWords; i++)
{
printf("%s \n", &(array[i]));
}
free(array[1]);
printWord(array[2])
}
Also, I want to make this function because I want to print every character of the word with a space before. It makes my program crash aswell.
void printWord(char **array)
{
for (int i = 0; i < strlen(*array); i++) printf("%c ", &((*array)[i]));
}
Don't know how to focus this. What do you recommend to me? Do you find any problems in my code? Thank you.