The function dstr_read given below reads a string from the keyboard into array buf, stores it in dynamically allocated memory and returns a pointer to it.
The function first reads a string from the keyboard into array buf of size 100. Then it allocates the exact memory required for this string using the malloc function and copies the string from the buffer to it. Finally, it returns a pointer to the string. As the size of buffer buf is set to 100, this function can be used to read strings such as the name of a person, email id, a line in an address, etc.
This function is used in the main function to read the first and last names of a person. Observe the calls to the free function to return to the system the memory used by strings fname and lname.
#include<stdlib.h>
char *dstr_read(char *msg)
{
char *str;
char buf[100]; /*buffer*/
printf(“%s”, msg);
scanf(“%s”, buf); /*read string in buffer*/
str = (char*) malloc(strlen(buf) + 1);
if (str == NULL) {
printf(“Error: out of memory …\n”);
exit(1);
}
strcpy(str, buf);
return str;
}
int main ()
{
char *fname, *lname;
printf(“Enter your name:\n”);
fname = dstr_read(“First name : “);
lname = dstr_read(“Last name : “);
printf(“Hi, %s %s\n”, fname, lname);
free(fname);
free (lname);
return 0;
}