DynStr.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/******************************************************************
Name: GetDynstr
Descr: Prompts user for a string, and input string, upto any length
Params: Prompt = Prompt to display before input, may be NULL
Returns: Dynamically-allocate string with user's input
Note: Caller is responsible for freeing memory.
******************************************************************/
char* GetDynStr( char* Prompt )
{
char *P = calloc(1,sizeof(char));
int Ch, Size=1;
if( P )
{
if( Prompt )
printf( "%s", Prompt );
while( (Ch=getchar()) != '\n' && Ch != EOF )
{
char *Tmp;
Tmp = realloc( P, Size+1 ); // +1 for new character, and terminator
if( !Tmp )
{
free( P );
return( NULL );
}
P = Tmp;
P[Size-1]=Ch;
P[Size++]='\0';
}
}
return(P);
}
void main()
{
char *Str;
if( (Str=GetDynStr( "Enter Name: " )) !=NULL )
{
printf("Hello %s\n", Str );
free( Str );
}
else
printf("Error: out of memory\n");
}