hey, are there any c programmers out there that want to help a fledgling figure out some funky behavior... in the next 2 hours? :p
specifically, i have this function:
[code]
void loadDict(char * fileName, int * numWords, char ** dict){
char * word;
FILE * filein = fopen(fileName, "r");
int i;
while(fgetline_113(&word, filein)) {
for (i = 0; i < *numWords; i++)
printf("dict[%d]: %s\n", i, dict[i]);
printf("\n");
dict[*numWords] = word;
(*numWords)++;
free(word);
}
}
fgetline_113 is a provided function that reads the next line from the file and stores it at the provided pointer; this is not the problem. What i'm expecting from this function is that it reads a list of about 7 words and inserts them into the array in order - this is a much simplified version of the actual lab. what i'm actually getting when i print it back out is the current word repeated numWords times, as though it's overwriting the words previously loaded into the dictionary.
dict is a pointer to a list of 50 char*s (malloc'd previously), and fgetline_113 mallocs memory for you and sticks the pointer in 'word', as mentioned... therefore, shouldn't i simply be able to say: element i of dict is assigned this pointer, then when i free it and re-malloc a new pointer, the old one - since it's a copy - should be untouched. instead what seems to be happening is it's copying the address just fine, but then that address is re-used by the next call to malloc... that is, it seems that my array is being filled with many copies of the same pointer...
any ideas??


Reply With Quote

