Re: Reading a string of unknown size



I have to read characters from stdin and save them in a string. The
problem is that I don't know how much characters will be read.

int main()
{
char *str = NULL, ch ;
int i = 0 ;
str = (char*) malloc (2*sizeof(char)) ;
*str = '\0' ;

while( (ch=getchar()) != '\n' )
{
*(str+i) = ch ;
i++ ;
str = (char*) realloc(str, (2*sizeof(char)) + i ) ;
}
*(str+i) = '\0' ;

printf("\n\n %s ", str) ;

getch() ;
return 0;
}


:)


--
Regards
Santosh S Nayak
E-Mail - santoshsnayak@xxxxxxxxx
WebPage -- http://santoshsnayak.googlepages.com

.



Relevant Pages