0

I have the following code, and i'm wondering how I can store each line of a text document into an array of pointers. I think im close but i'm getting a few errors.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{

    FILE * fp;
    char buffer[50];
    int totalSize;
    totalSize = 6;
    int size = 0;
    char * array;

    fp = fopen(location,"r");


    while (fgets(buffer,150,fp) != NULL)
    {
        array = malloc(sizeof(strlen(buffer))+1);
        strcpy(array[size],buffer);
        size++;
    }

    for (int x = 0; x < size ; x++)
    {
        printf("%s",array[x]);
    } 

    free(array);
    return 0;
}
  • the `sizeof(strlen(buffer))` is a very interesting construct, which at the first glance I am failing to interpret. Anyway, this is obviously not doing what you intend. `strlen` alone will be enough here. – Eugene Sh. Feb 18 '15 at 19:58
  • `strcpy(array[size],buffer);` - your compiler should be throwing a warning about this line, heed it! `strcpy` expects a `char*`, and you're passing it a `char`. You probably want to take the address of it ;). – slugonamission Feb 18 '15 at 19:58
  • And `malloc`-ing stuff in a loop, but freeing it once should ignite some red lights in your head. – Eugene Sh. Feb 18 '15 at 19:59
  • 1
    You declare buffer to be an array of 50 characters, yet in your fgets statement you are reading up to 150 characters into that buffer (i.e. a buffer overflow). Also, each time through the loop you will be assigning a new memory location to array leading to a lot of dangling pointers. – thurizas Feb 18 '15 at 20:01

1 Answers1

1

Your array should be an array of pointers. You have lines (so an array of lines), each line being a C-string (a pointer to a NUL terminated char array). So you need to declare your variable as char **array = NULL.

Now, each time you read a line you must alloc a new entry in your array of lines, this way array=realloc(array,(size+1)*sizeof(char *)) then read a buffer, allocate memory to store the string read with array[size]=malloc(strlen(buffer)+1) and then copy strcpy(array[size],buffer) then increment the size++.

You must free everything accordingly (free all pointers and then free the array). Also, take care about sizes, buffer is 50 but you tried to read 150... Be consistent.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
  • Thanks, everything you wrote worked, except when it reads the first line, for some reason it is giving me stuff like this: ?K?p? instead of the actual line. First i do the realloc, then i malloc, copy it and increment the size – BeginnerC96 Feb 18 '15 at 20:31
  • Extending 'array' by a single element each iteration calls to mind the tale of Shlemiel and the painter's algorithm ... – jschultz410 Feb 18 '15 at 20:38