#include <stdio.h>
#include <string.h>
#define BLOCK 10
#define TRUE 1
#define MAX_WIDTH 80 //console size, can be changed
char * JustifyText(char const* str, int width); //Прототип функции
int main(void)
{
char *st_point = (char *)malloc(BLOCK);
char *cur_point = st_point;
char *cpy_point = st_point; //copy for memory cleaning
unsigned r_pos, current_size = BLOCK, width;
if(st_point == NULL)
{
printf("Error of memory allocation!\n");
return -1;
}
printf("E11: Text alignment\nInput width:\n");
do{
scanf("%i", &width );
if(width <= 0 || width > MAX_WIDTH)
printf("Incorrect input, please, try again!\n");
}while(width <= 0 || width > MAX_WIDTH);
getchar(); //miss enter once!
printf("Input text for alignment (press <Enter> x 2 to stop) :\n");
printf("START ADRESS: %i\n", st_point);
while(TRUE) // Exit == press <Enter> x 2
{
*cur_point = getchar();
r_pos = cur_point - st_point; //relative position
if(r_pos)
if(*cur_point == '\n' && *(cur_point - 1) == '\n')
{
*cur_point = 0; //делаем строку
break;
}
if(r_pos >= current_size) //динамически выделяем память
{
current_size += BLOCK; //увеличиваем
st_point = (char *)realloc(st_point, current_size);
if(st_point != cpy_point)//перенос
{
free(cpy_point);//здесь кроется основная ошибка? но почему?
cpy_point = st_point;
cur_point = st_point + r_pos;
}
}
++cur_point;
}
puts(st_point);
return 0;
}