yeah. er. I shall explain! I am trying to write a function that parses through a text file which contains a word on each line, then returns an array of strings of a certain size (that is, all strings that contain, say, 4 chars are put into an array). to do this. I parse through the file twice, first time to determine how many strings are of that size. then I initialise a char ** to that size. second time, all strings of that size are given the appropriate value. right, all of this basically works fine. here's the weird thing : when I try to print out the values after they have been assigned to their separate values in the array, it prints out the correct number of values, it's just that they are all the very last string in the file, which usually isn't even the right size. however, if I print out the string that is supposed to be assigned to the array from within the if statement, it prints the correct one. it only seem to go wrong when I assign. I have no idea why this is. if that wasn't too clear, here is the cod :
Code:
void parselist (int length, FILE *list, char **parsedlist)
{
char string[100];
int compare, sizeoflist = 0, i = 0;
char *word;
while (fgets(string, 100, list) != NULL)
{
if (length == strlen(string) )
{
sizeoflist++;
}
}
parsedlist = calloc(sizeoflist, sizeof(char) );
fseek(list, 0, SEEK_SET);
while (fgets (string, 100, list) != NULL)
{
if (strlen(string) == length)
{
parsedlist[i] = string;
i++;
}
}
for (i = 0; i < sizeoflist; i++)
{
printf("%s", parsedlist[i]);
}
}
which does not work.
Code:
void parselist (int length, FILE *list, char **parsedlist)
{
char string[100];
int sizeoflist = 0, i = 0;
char *word;
while (fgets(string, 100, list) != NULL)
{
if (length == strlen(string) )
{
sizeoflist++;
}
}
parsedlist = calloc(sizeoflist, sizeof(char) );
fseek(list, 0, SEEK_SET);
while (fgets (string, 100, list) != NULL)
{
if (strlen(string) == length)
{
printf("%s", string);
}
}
which prints out correct values.
I suppose it's something obvious. any ideas? =/