c - dynamically allocated char array only prints first character from each index -


i'm trying read file has words in separated spaces, words read within loop. read correctly within loop , can printed loop ends able print first character of each element. here code:

char **storewords(char **words){      char* filename = "words.txt";     file* fp = fopen(filename, "r");     int i;     (i = 0; < 2; i++){         int j;         (j = 0; j < 20; j++){             fscanf(fp, "%s", &words[i][j]);             printf("%s", &words[i][j]); //prints correctly         }     }     printf("%s", &words[0][0]); //prints first character of selected element     fclose(fp);     return **words; }  int main(){     char **words = (char**)malloc(6 * sizeof(char*));     (int = 0; < 6; i++){         words[i] = (char*)malloc(20 * sizeof(char));     }     storewords(words);     system("pause");    return 0; } 

i don't understand why happens, appreciated if explained. thanks.

the problem allocating 2d array of chars, not 2d array of strings.

this pointer string, or 1d array of chars:

char* 

this pointer 1d array of strings, or 2d array of chars:

char** 

and pointer 2d array of strings, or 3d array of chars:

char*** 

you trying store string char, , reason didn't crash because allocated [6][20] array iterated on 2x20 words, there room overflow.

so, in main function need allocate (note don't need cast pointer returned malloc):

char ***words = malloc(6 * sizeof(char**)); (int = 0; < 6; i++){     words[i] = malloc(20 * sizeof(char*));         } 

change function declaration use new type:

char ***storewords(char ***words) 

then when read in words, use temp char buffer , dynamically allocate enough space based on word size:

for (j = 0; j < 20; j++){     char word[100]; // max word size of 100 chars     fscanf(fp, "%99s", word);     words[i][j] = malloc(strlen(word) + 1);     strcpy(words[i][j], word);     printf("%s", words[i][j]); //prints correctly } 

note when print out word don't need use ampersand, because words[i][j] contains char* not char:

printf("%s", words[0][0]); 

Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

datatable - Matlab struct computations -