Output says all array values are “anxiety” when the words of file fileIn are printing correctly and in order. My problem may be in the realloc()?
ReadIn = malloc(sizeof(char) * 50);
while(fscanf(fileIn, "%s", ReadIn) != EOF){
wordlist = (char **)realloc( wordlist, (numwords + 1) * sizeof(char*));
printf("%s\n",ReadIn);
wordlist[numwords] = ReadIn;
numwords++;
}
for(i = 0; i < numwords; i++){
printf("%d %s\n", i , wordlist[i]);
}
Output:
This
is
a
journey
into
fear
and
anxiety.
0 anxiety.
1 anxiety.
2 anxiety.
3 anxiety.
4 anxiety.
5 anxiety.
6 anxiety.
7 anxiety.
You make each array pointer point to the
ReadInbuffer, which will contain the last string that was read in.You want to duplicate each string that’s read in:
You should also take care to free each of those strings when you’re done with the
wordlistarray.And if your compiler’s runtime library doesn’t have the non-standard, but common,
strdup()function, it’s easy to implement (or find a public domain version of).