user19435240
user19435240

Reputation:

C string array overwrites index

I have a bit of code that I'll show here

// open file
FILE *file = fopen(filename, "rb");

// create buffer & lines array
char buffer[512];
char *lines[512];

// create index
int length = 0;
while (fgets(buffer, sizeof(buffer), file))
{
    // update & test
    lines[length] = buffer;
    printf("(1) %s", lines[length]);

    // ++
    length++;
}

// print nl separator
printf("\n");

// output
for (int i = 0; i < length; i++)
    printf("%s\n", lines[i]);

The output in the console is this:

(1) line 1
(1) line 2
(1) line 3
line 3
line 3
line 3

Even though I'm not overwriting anything in the second loop. Why is it doing this, and how can I solve this?

Upvotes: 1

Views: 35

Answers (0)

Related Questions