My program reads words from a file, and stores them in a dynamically allocated array as a number of words.
My problem is while in the while loop when I print the array, it seems to pointing to the correct word. After the code falls through the while loop, when I print all the indicies, 'ice' is the last word, and I am trying to find out why.
FILE *fileptr=fopen("file.txt","r");
char** DataArray;
int num_of_words=0;
char str[10];
while(fscanf(fileptr,"%s",&str)!=-1)
{
num_of_words++;
}
DataArray=(char**)malloc(num_of_words*sizeof(char*));
rewind(fileptr);
int i=0;
while(fscanf(fileptr,"%s",&str)!=-1)
{
printf("%s",str);
int len=strlen(str);
printf("\t%d",len);
DataArray[i]=(char*)malloc(len*sizeof(char));
DataArray[i]=str;
printf("\t%s\n",DataArray[i]);
i++;
}
printf("\n");
//printf("%s\n",*(DataArray+2));
printf("%s\n",DataArray[0]);
printf("%s\n",DataArray[1]);
printf("%s\n",DataArray[2]);
fclose(fileptr);
Output:
apple 5 apple
mango 5 mango
ice 3 ice
ice
ice
ice