I need to return a list of strings. Those strings are read from the file (each string in each line of the file). The code below is not working:
void getStrings(char **container, FILE* file, int *numberOfLetters) {
char* line = NULL;
size_t l = 0;
ssize_t r;
container = (char**) malloc (sizeof(char*));
size_t lettersNumber= 1;
size_t numberOfStrings = 0;
size_t sizeOfContainer = 1;
while ((r = getline(&line, &l, file)) != -1) {
line[strlen(line) - 1] = '\0';
lettersNumber = lettersNumber + strlen(line);
if (numberOfStirngs == sizeOfContainer) {
sizeOfContainer= sizeOfContainer * 2;
char** temp = calloc(sizeOfContainer, sizeof(char**));
for (int k = 0; k < l; k++) {
temp[k] = container[k];
}
free(container);
container = temp;
}
container[numberOfStrings] = line;
numberOfStrings++;
}
if (line) {
free(line);
}
Because you calloc
the whole array of pointers in each step, you loose all the strings from previous iterations and always only keep the last line. Since you use calloc
, all these pointers are null, thus your error message.
The tool that is foreseen for such things is realloc
and not malloc
or calloc
to keep the values that you already have stored.
There seem to be other things wrong, too. Eg you have only one line
, all your lines are copied into that one, so previous lines are always overwritten. As BLUEPIXY correctly notes, you only change the value of your function parameter to the new values, you never return the new value to the caller.
Then, re-allocating memory in each iteration is a real waste. You should think of a strategy to do that more efficiently.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.