Когда вы инициировали значение nwords
, вы перезаписывали его адрес указателя, а не его значение.
Кроме того, как говорит комментатор, строка char **words = malloc(sizeof(char));
неверна. Но вы всегда перераспределяете переменную words
, поэтому код по-прежнему работает, как и ожидалось. Чтобы сделать его супер безопасным, вы должны изменить его на char **words = malloc(sizeof(char*));
Я использую строку *nwords = 0;
и теперь она работает как положено.
#define BUFSIZ 1000
#include<stdio.h>
// This function puts every word found in a text file, to a String array, **words
char **concordance(char *textfilename, int *nwords){
FILE * fp;
char *fileName = strdup(textfilename);
fp = fopen(fileName, "r");
if(fp == NULL) {
perror("fopen");
exit(1);
}
char **words = malloc(sizeof(char));
// char **words = NULL
char line[BUFSIZ];
while(fgets(line, sizeof(line), fp) != NULL){
char *word = strdup(line);
word = strtok(word, " ");
printf("word='%s'\n",word);
do{
*nwords=*nwords+1;
printf("nwords=%d\n",*nwords);
words = realloc(words, (*nwords+1) * sizeof(char(*)));
words[*nwords] = word;
} while((word = strtok(NULL, " ")) != NULL);
}
return words;
}
int main(int argc, const char * argv[]) {
int *nwords = malloc(sizeof(int));
*nwords = 0;
concordance("test.txt", nwords);
}