C Programming Task on Ragged Array

C Programming Task on Ragged Array

#include <stdio.h>
#include <string.h> //for string manipulation
#include <unistd.h>
#include <stdlib.h>

#define BUFFER_SIZE 1024
#define STEP_LINES 5

int main (int argc, char *argv[]){

FILE *ifile = stdin; // inputfile, initit as stdin
int line_count=0, capacity = STEP_LINES, i;
char buf[BUFFER_SIZE]={0}; // for no exceed more than BUFFER_SIZE length {0} = init everything with 0

char *buf_ptr = NULL;
char **ragged_array;

ragged_array = (char**)malloc(capacity * sizeof(char*));

buf_ptr = fgets(buf, BUFFER_SIZE, ifile);
while (buf_ptr != NULL){
int len = strlen(buf_ptr) + 1;
ragged_array[line_count] = (char *)malloc(len * sizeof(char));
strcpy(ragged_array[line_count], buf_ptr);
line_count++;
if (line_count == capacity) {
capacity += STEP_LINES;
ragged_array = realloc(ragged_array, capacity * sizeof(char*));
}
buf_ptr=fgets(buf, BUFFER_SIZE, ifile);
}

for (i = 0; i<line_count; i++) {
printf(“%3d: %s”, (i+1), ragged_array[i]);
}
for (i = 0; i<line_count; i++) {
free(ragged_array[i]);
}
free(ragged_array);

return(EXIT_SUCCESS);
}