#include <stdio.h>
#include <stdlib.h>
// Our new variable-length prompt function...but it doesn't
// quite work. Try and identify and fix the problem.
char *prompt(char *mesg)
{
int cur_array_len = 2;
int pos = 0;
char ch;
char *text = NULL;
printf("%s", mesg);
// FIX: the initial malloc needs to be outside the array, otherwise
// it interferes with the expanding part of the loop.
text = malloc(sizeof(char) * cur_array_len);
do
{
scanf("%c", &ch);
if(ch == '\n')
{
text[pos] = '\0';
}
else
{
text[pos] = ch;
pos++;
if(pos == cur_array_len - 1)
{
// expand array
char *t2 = malloc(sizeof(char) * cur_array_len * 2);
int i;
for(i = 0; i < cur_array_len; i++)
{
t2[i] = text[i];
}
cur_array_len *= 2;
free(text);
text = t2;
}
}
} while(ch != '\n');
return text;
}
// The original, fixed-size prompt function for reference.
char *org_prompt(char *mesg, int max_length)
{
char *text = malloc(sizeof(char) * max_length);
printf("%s", mesg);
scanf("%s", text);
return text;
}
int main(int argc, char *argv[])
{
char *name = prompt("Enter name: ");
printf("Hello %s, how are you?\n", name);
free(name);
}