#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_SIZE 100
#define INITIAL_BUFFER_SIZE 16
int main() {
char **line_buffer;
line_buffer = (char **) malloc(INITIAL_BUFFER_SIZE);
int i = 0;
int lines = 0;
// the size of buffer
int buffer_size = 1;
int *buffer_size_p = &buffer_size;
char *line_one = (char *) malloc(MAX_LINE_SIZE);
//read lines from a file
while (gets(line_one)) {
line_buffer[lines] = (char *) malloc(MAX_LINE_SIZE);
strcpy(line_buffer[lines], line_one);
lines++;
line_one = (char *) malloc(MAX_LINE_SIZE);
// if too much lines double the buffer size
if (lines == *buffer_size_p) {
buffer_size *= 2;
line_buffer = IncreaseBuffer(line_buffer, buffer_size_p);
}
}
PrintLines(line_buffer, lines);
// sorting all the line by strcmp
for (i = 0; i < lines; i++) {
printf("%s", line_buffer[i]);
// int min = MinLineIndex(line_buffer, i, lines);
// SwapLines(line_buffer, i, min);
}
PrintLines(line_buffer, lines);
// free(line_buffer);
return 0;
}
First, ignore the gets() function, this is required for this.
First, I used a for loop to do (char *) line_buffer[lines] = (char *) malloc(MAX_LINE_SIZE);
It does not work;
I did this way, it worked, However, after read several lines from a file, the first line become something like "��R", and it is changing every time.
And, I cannot use free(line_buffer); as well.
Self studying. Please help.