I have this code, which I expect from to read a single character from user, then re-print it, then realloc'ing new memory to store the next character that user will enter; all this repeating until the user enters the '1' character. However, my program does nothing until the user presses 'return', then echoes back the entire string. Why does it behave like this?
#include <stdlib.h>
#include<stdio.h>
int main()
{
char *s = (char *)malloc(sizeof(char));
int i = 1 ;
do
{
scanf(" %c",s+i-1);
printf("%c" , *(s+i-1));
i++ ;
s = (char *)realloc(s , sizeof(char)*i);
}while(*(s+i-1) != '1');
printf("\n\n %s" , s);
return 0;
}
This is what I expect:
h // input from user
h // the output
w // input from user
w // output from user
But this is what I get:
what // input from user
what // output
I tried to replace scanf
by getchar
, but that doesn't help.