I'm given an unknown amount of "wide symbols". The text is formatted as sentences, which i have to add to struct "Text".
These are my structs:
struct Sentence {
wchar_t *sentence;
int amount_of_symbols;
};
struct Text {
struct Sentence *sentences;
int amount_of_sentences;
};
I dynamically allocate memory for array of "Sentence" structs and add them. This is my input code:
int amount_of_sentences = 0;
struct Sentence *sentences = (struct Sentence *) malloc(amount_of_sentences * sizeof(struct Sentence));
struct Text text = {sentences, amount_of_sentences};
wchar_t symbol;
int buffer_size = 0;
wchar_t *buffer = (wchar_t *) malloc(buffer_size * sizeof(wchar_t));
bool sentence_begun = true;
while (true) {
symbol = getwchar();
if (symbol == '\n')
break;
if (sentence_begun && symbol == ' ') {
sentence_begun = false;
continue;
}
buffer = (wchar_t *) realloc(buffer, (++buffer_size) * sizeof(wchar_t));
buffer[buffer_size - 1] = symbol;
if (symbol == '.') {
buffer[buffer_size] = '\0';
text.amount_of_sentences++;
text.sentences = (struct Sentence *) realloc(text.sentences, text.amount_of_sentences * sizeof(struct Sentence));
text.sentences[text.amount_of_sentences - 1].amount_of_symbols = buffer_size;
text.sentences[text.amount_of_sentences - 1].sentence = (wchar_t *) malloc(buffer_size * sizeof(wchar_t));
text.sentences[text.amount_of_sentences - 1].sentence = buffer;
buffer_size = 0;
buffer = (wchar_t *) realloc(buffer, buffer_size * sizeof(wchar_t));
sentence_begun = true;
}
}
Everything seems to be fine, but as soon as i try to output all my sentences, not all of them are shown and some of the are repeated.
This is my output code:
for (int i = 0; i < text.amount_of_sentences; i++) {
wprintf(L"%ls\n", text.sentences[i].sentence);
}
Example of input-output:
adjsand. asdad.a.a. aaaa. adsa.
a.
adsa.
adsa.
What can be wrong with this code and what should i change?