I'm a beginner programmer, I got a home assignment to seperate a string into words, and put each word in an array of strings. We are practicing dynamic memory allocations. the assignment says that the size of the array must be [10] and i need to change the size of the array with malloc accoring to the number of words in the string, and allocate room for every word in the array. when i reach the end of the programm and free the allocated memory it says "Project.exe has triggered a breakpoint" and i can't find my mistake in the code.
P.S this is my first question on stack so i apologize in advance if I posted wrong somehow.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void fillArray(char string[], char* array[], int* pointer);
int countCharacters(char string[], int index, int* pointer);
void freeArray(char* arr[], int size);
void main()
{
char string[] = { "i have two dreams" };
printf("Your sentence is: %s", string);
int sentenceLength = 1;
for (int i = 0; string[i] != '\0'; i++)
{
if (string[i] == ' ') sentenceLength++;
}
int* point = &sentenceLength;
char* array[10];
fillArray(string, array, point);
printf("\n\nYour array is: \n");
for (int i = 0; i < *point; i++) puts(array[i]);
freeArray(array, *point);
}
void fillArray(char string[], char* array[], int* pointer)
{
*array = (char*)malloc(*pointer * sizeof(char));
if (array == NULL)
{
printf("--NO MEMORY--");
exit(1);
}
int i = 0;
int j = 0;
for (i; i < *pointer; i++)
{
array[i] = (char*)malloc(sizeof(char) * countCharacters(string, j, pointer));
if (array[i] == NULL)
{
printf("--NO MEMORY--");
exit(1);
}
for (j; string[j] != ' '; j++)
{
if (string[j] == '\0')
{
array[i][j] = '\0';
return;
}
array[i][j] = string[j];
}
if (string[j] == ' ' || string[j] == '\0')
{
array[i][j] = '\0';
j++;
}
}
}
int countCharacters(char string[], int index, int* pointer)
{
int size = 1;
if (string[index] == ' '&& index<= *pointer) index++;
for (index; string[index] !=' '&& string[index]!='\0'; index++)
{
size++;
}
return size;
}
void freeArray(char* arr[], int size)
{
for (int i = 0; i < size; i++)
{
free(arr[i]);
arr[i] = NULL;
}
}