I am new in C. I play with a dynamic array of strings. I want to load all words from textfile into an array of strings. I dynamically add items into array. It almost works, but when I want to print them out I got words repeated. I think the problem is in dictionary = (char **)realloc(dictionary, sizeof(char *) * (idx));
The array should be increased by one with original data copied.
int main() {
FILE *fr;
int i = 0;
int c;
const char *path = "..../sample.txt";
char *word;
char **dictionary;
word = (char *)malloc(sizeof(char));
dictionary = (char **)malloc(sizeof(char *));
int idx = 0; // index of word
int widx = 0; // index of char in word
fr = fopen(path, "r");
while((c = getc(fr)) != EOF){
if( c == ' '){
widx++;
word = (char *)realloc(word, sizeof(char) * (widx));
*(word + widx-1) = '\0';
idx++;
dictionary = (char **)realloc(dictionary, sizeof(char *) * (idx));
*(dictionary+idx-1) = word;
widx = 0;
word = (char *)realloc(word, 0);
}
else if( c == '.' || c == ',' || c == '?' || c == '!' ){
// skip
}
else{
widx++;
word = (char *)realloc(word, sizeof(char) * (widx));
*(word + widx-1) = (char)c;
}
}
fclose(fr);
// print words
int n = idx;
for(i = 0; i < n; i++){
printf("%d - %s \n", i, *(dictionary+i));
}
return 0;
}
Output:
0 - shellbly
1 -
2 - shellbly
3 - Bourne-derived
4 - shellbly
5 - Bourne-derived
6 - shellbly
7 - Bourne-derived
Expected:
1 - The
2 - original
3 - Bourne
4 - shell
5 - distributed
6 - with
7 - V7
8 - Unix
I must do something wrong. Thanks for any feedback.