I'm trying to read a text file called "olaola.dict", some sort of a dictionary, that currently holds 10 words each with 5 letters and store the words into an array of strings. I'm using a char** pointer that points to an array of pointers in which each pointer points to a word from the dictionary.
So far, I've developed this code. It is printing the last 7 words correctly, but not the first three. The code is the following:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define ROW 10 /* 10 words */
#define COL 6 /* 5 letters in each word Null terminator*/
int main(void) {
int i, j;
FILE *fp = NULL;
char **ptr = NULL;
ptr = (char**)malloc(ROW * sizeof(char*));
fp = fopen("olaola.dict","r");
for (i=0 ; i < 15; i ) {
if ((ptr[i] = malloc(sizeof(char) * COL)) == NULL) {
printf("unable to allocate memory \n");
return -1;
}
fscanf(fp, "%s", ptr[i]);
}
for(i = 0; i < ROW; i ){
printf("Word %d:%s\n", i 1,ptr[i]);
}
for (i=0 ; i < ROW; i )
free(ptr[i]);
free(ptr);
fclose(fp);
return 0;
}
/*
ptr[] 0 1 2 3 4 5 6
-------- --- --- --- --- --- --- ---
| --|------->| w | o | r | d | 0 | 0 |\0 |
-------- --- --- --- --- --- --- ---
| --|------->| w | o | r | d | 0 | 1 |\0 |
-------- --- --- --- --- --- --- ---
| --|------->| w | o | r | d | 0 | 2 |\0 |
-------- --- --- --- --- --- --- ---
| --|------->| w | o | r | d | 0 | 3 |\0 |
-------- --- --- --- --- --- --- ---
| --|------->| w | o | r | d | 0 | 4 |\0 |
-------- --- --- --- --- --- --- ---
*/
The output is:
Word 1:[p:�
Word 2:0[p:�
Word 3:P[p:�
Word 4:Carlo
Word 5:Andre
Word 6:MESSI
Word 7:Arroz
Word 8:Doces
Word 9:Carro
Word 10:Tevez
Here is also the text file olaola.dict
lista
Sabes ontem Carlo
Andre
MESSI
Arroz Doces Carro Tevez
As you can see, there is no specific position for the words to be. What would be the correct way to solve this problem? (In another note, would it be wiser and more efficient to use a 2D array, even though the dictionary can have like 5k words ?)
CodePudding user response:
I noticed that the first for loop goes from zero to 14 instead of from zero to 9. This means that the code writes beyond the boundaries of the array. I assume that this writes to the memory being allocated for the first 3 words and this is the reason why you see the wrong values for these words. Correct the for loop and see if this solves the issue.
CodePudding user response:
you problem is in this line
for (i=0 ; i < 15; i ) {
it's supposed to be:
for (i=0 ; i < ROW; i )
because you should allocate till ptr[9]
, but you are allocating till ptr[14]
which will produce undefined behavior as the size of the array = 10