BeginnerC96
BeginnerC96

Reputation: 9

Reading in values using pointers

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;
}

Upvotes: 0

Views: 61

Answers (1)

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36401

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.

Upvotes: 1

Related Questions