getline line by line and then store entire lines in an array in C [closed]

梦想与她 提交于 2019-12-01 14:33:09

As already has been mentioned, you need to allocate space for pointers, not chars:

char **array;
array = malloc(bufsize * sizeof(char*));

Also you need to allocate space for separate lines, and copy lines to it:

while ((getline(&line, &bufsize, fp)) != -1) {
  printf("%s", line);
  array[i] = malloc(strlen(line) + 1);
  strcpy(array[i], line);
  i++;
} 

A mistake in your code is that all array[i] points to the same string in variable line, which is refilled by getline() every loop cycle.

It may be useful to read manual about getline. It permits allocation of strings by itself, but don't forget to use free().

array[0] = NULL;
while ((getline(&array[i], &bufsize, fp)) != -1) {
  printf("%s", array[i]);
  array[i + 1] = NULL;
  i++;
} 
char **array;



array = malloc(bufsize * sizeof(char));

array[i] = line;

I think your problem is with array, you are indeed dynamically allocating memory for array but not array[i].

while ((getline(&line, &bufsize, fp)) != -1) { 
array[i]=malloc(sizeof(char) * (bufsize+1));
printf("%s", line);
array[i] = line;
i++;

}

This should fix it

Edit after testing the program:

array = malloc(bufsize * sizeof(char));

should be

array = malloc(bufsize * sizeof(char*));
Fantastic Mr Fox

This does not make an array of strings:

char **array;
array = malloc(bufsize * sizeof(char));

There are plenty of resources that describe how to do this. eg. How to create a dynamic array of strings. Essentially, you need to allocate space for the array, then allocate space for each the strings, a standard way might be:

char **arrayOfStrings;
unsigned int numberOfElements = 20, sizeOfEachString = 100;
arrayOfStrings = malloc(numberOfElements * sizeof(char*));
for (int i = 0; i < numberOfElements ; i++)
    arrayOfStrings[i] = malloc(sizeOfEachString  * sizeof(char));

As a further note, for your whileloop:

while (getline(&line, &bufsize, fp)) {

Is sufficient. Getline will return 0 once you have finished your file. Read this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!