There are some notes here:
1. You could have used getline() function instead of scanning characters one by one.
2. Assuming that for now we want to use scanf, you might not now the paragraph's length beforehand, so its better to use a linked list of lines in which you allocate memory dynamically. Here is a working example:
#include <stdio.h>
#include <stdlib.h>
typedef struct _line{
char * chars_in_line;
struct _line * next_line;
}line;
void fill_paragraph_lines(line * first_line , int max_size){
first_line->chars_in_line = (char *)malloc(max_size * sizeof(char));
first_line->next_line = NULL;
line * current_line = first_line;
int i;
char aux = '\0';
while(1){
for(i = 0 ; i < max_size ; i++){
if(aux == '\0'){
printf("enter a character: ");
scanf(" %c" , &aux);
}
// if the received character is not '\n' put that in line
if(aux != '\n'){
current_line->chars_in_line[i] = aux;
aux = '\0';
}
// if you receive \n as an input character, set the ending \0 and break from for loop
else{
current_line->chars_in_line[i] = '\0';
aux = '\0';
break;
}
// reset aux character to its initial value
aux = '\0';
// if you reach max_size also end the string with '\0', no matter what character you received from user
if(i == max_size - 1){
current_line->chars_in_line[i] = '\0';
printf("\nmax line characters reached\n");
aux = '\0';
}
}
// the user can end a paragraph by inputting \n, when previous line is completed
char possible_paragraph_ending;
printf("enter a character: ");
scanf(" %c" , &aux);
if(aux == '\n')
return;
// if the user inputs another character, start a new line
line * new_line = (line*)malloc(sizeof(line));
new_line -> chars_in_line = (char *)malloc(max_size * sizeof(char));
new_line ->next_line = NULL ;
// chain the new line to the previous lines and move the pointer current line to the
// newly created line
current_line->next_line = new_line;
current_line = new_line;
}
}
void destroy_paragraph(line * first_line){
if(first_line == NULL)
return ;
line * traverse_line = (line *)first_line->next_line;
line * dealloc_line = first_line;
while(1){
free(dealloc_line->chars_in_line);
free(dealloc_line);
if(traverse_line == NULL)
return;
dealloc_line = traverse_line;
traverse_line = dealloc_line->next_line;
}
}
void print_paragraph(line * first_line){
line * traverse_line = first_line;
while(traverse_line != NULL){
printf("%s\n" , traverse_line->chars_in_line);
traverse_line = traverse_line->next_line;
}
}
int main() {
line * first_line = (line *)malloc(sizeof(line));
fill_paragraph_lines(first_line , 10) ;
print_paragraph(first_line);
destroy_paragraph(first_line);
return 0 ;
}
In the code above, you need to hit enter after each character in a line. If you want to end a line, you have to press Return 2 times consecutively and you need to press Return 3 times to end a paragraph.
When a new line needs to be generated, memory is dynamically allocated. destroy_paragraph() needs to be called to free memory.