Hi (first post :) ),
I have a coursework where we have to read in 50 lines from a file (bubble.txt), sort them into length order and then print them out (its not the whole coursework, just a part). I thought that the only way of holding lines of text in an array is to hold a pointer to each char array in an array called strings.
For some reason (I must admit, pointer do confuse me a bit), whenever I run this code below (just to make sure the lines are in the array) i keep getting the last line (line 50) printed 50 times and I can't tell why.
Any help appreciated.
Kristian Brimble
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "string.h"
char *strings[50];
void readLines(void);
void printLines(void);
int main()
{
readLines();
printLines();
return 0;
}
void readLines(void)
{
FILE *inputFilePtr;
inputFilePtr = fopen("bubble.txt", "r");
char line[1000];
for(int i = 0; i < 50; i++)
{
fgets(line, 1000, inputFilePtr);
char *linep = malloc(sizeof(char) * 1000);
linep = (char *)&line;
strings[i] = linep;
}
}
void printLines(void)
{
for(int i = 0; i < 50; i++)
{
printf("%s", strings[i]);
}
}