I read words from given file (dictionary) to single string and I assign the string to nth index of string array. But it does not work. Output of the for loop in the main() is always e3V\347 etc. and output of the for loop in the createWordTable() is always last word of dictionary. Here is my code
char** createWordTable();
char** createTable();
int main()
{
int i;
char **hashTable;
hashTable = createTable();
hashTable = createWordTable();
for (i=0; i< 338; i++) {
printf("%s \n",hashTable[i]);
}
return 0;
}
char** createWordTable(){
char word[20],**table;
FILE *dicFile;
table = createTable();
dicFile = fopen("smallDictionary.txt", "r");
if (dicFile == NULL) {
perror("error");
}
int wordCount = 0,endFile = 1;
while (endFile != EOF) {
endFile = fscanf(dicFile,"%s",word);
table[wordCount] = word;
wordCount = wordCount+1;
}
for (int i=0; i< 338; i++) {
printf("%s \n",table[i]);
}
return table;
}
char** createTable(){
char **table;
int i;
table = (char **)malloc(338 * sizeof(char *));
for (i=0; i<=338; i++) {
*table = (char *)malloc(25 * sizeof(char));
}
return table;
}
I changed code to this and its work! I defined global variable 'table' and removed pointers (also dynamic allocation functions). I'm very curious why pointers don't work with array of strings in C for this code (I know square brackets also mean 'pointer') ? Because i have no bad experience with integer arrays. Sorry for bad English, here is new code :`
char words[338][10];
int main()
{
createWordTable();
for (int i=0; i< 338; i++) {
printf("%s \n",words[i]);
}
return 0;
}
void createWordTable(){
char word[20];
FILE *dicFile;
dicFile = fopen("smallDictionary.txt", "r");
if (dicFile == NULL) {
perror("error");
}
int wordCount = 0;
while (!feof(dicFile)) {
fscanf(dicFile,"%s",word);
if(feof(dicFile)) break;
strcpy(words[wordCount], word);
wordCount = wordCount+1;
}
fclose(dicFile);
}`