Basically:
i'm fetching characters out of a text file. Each word ends with a
\n
in the text file.
I want to create an char **
array that will include ONLY the first character of each word.
To do that, i'm scanning the text file and running on my chars
array.
If the current char
is a \n
replace it with a null terminator \0
when inserting to the chars
array.
In that way, i'll be able to seperate between words
when i'll run on that array with my char **words_arr
.
I want the **words_arr
to point at every first character of a word, which means one char after each \0
which indicates on an end of a word.
size_t words = 1, total_characters = 30;
char **original_address, **words_arr, *chars, character;
chars = (char *)malloc(sizeof(char) * total_characters);
words_arr = original_address = (char **)malloc(sizeof(char *) * (words);
while (i < total_characters)
{
character = fgetc(text_file);
if (character == EOF)
{
break;
}
if (character == '\n')
{
*chars = '\0';
*words_arr = chars + 1;
++words;
words_arr = (char **)realloc(original_address, sizeof(char *) * (words));
words_arr += words-1;
}
else
{
*chars = character;
}
++chars;
++i;
}
Also, I have no idea how many words will I have, and that is why I use the realloc
function, although i'm not sure i'm doing it right.
For now, i'm able to print the chars
array and see all the words and each word starts at a new line.
But when I try to print the words
array, i'm getting a segmentation fault.
I'm trying to print them using:
i = 0;
chars -= total_characters;
while (i < total_characters)
{
runner = chars + i;
if (*runner == '\0')
{
printf("\n");
}
else
{
printf("%c", *runner);
}
++i;
}
printf("\n\n");
words_arr -= words;
i = 0;
while (i < words)
{
printf("%s", *(words_arr + i));
++i;
}
As I said, the first print, or chars
array successes.
The second print, of words_arr
returns a Segmentation fault
.
Thanks.