C: Unable to store lines from a file into an array

1479 views c

This is some code I used to read and store lines from a text file into an "expressions" array:

//create array for going through the file
char lines[128];
//create array for storing expressions
char **expressions = malloc(128*sizeof(char*));

FILE *file = fopen(argv[1],"r");
int count = 0;
while (fgets(lines,128,file)){
    expressions[count] = lines;
    printf("expressions[%d] is %s\n",count,expressions[count]);

for (int i = 0; i<count; i++){

And this is the text this code is trying to read:

f = g + h - 42;

g = 12 + 23;

My issue here is that while it appears to go through the file properly (count matches the number of lines), the final print loop prints the last line (g = 12+23) twice instead of the two distinct lines. Why is this occuring and what can I do to fix this issue?

answered question

1 Answer


Each time you read a line, you store it in the lines character array, and then you save the address of that array in the next space of expressions. If you look at the values stored in expressions you'll find that they are all the same.

If you want to keep a copy of each line, you're going to have to have space to store a copy of each line. If you have a maximum number of lines which you're going to deal with, you can allocate that memory in the program. Otherwise you're going to have to start using dynamic memory allocation.

Let's work on 100 lines maximum, with each line no longer than 127 characters (as above):

char expressions[100][128];

int count = 0;
while (fgets(lines,128,file)) {
    strcpy(expressions[count], lines);
    printf("expressions[%d] is %s\n",count,expressions[count]);

    if (count == 100)

posted this

Have an answer?


Please login first before posting an answer.