Solution for Exercise 05_09-yourname.c
05_09-yourname.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
const int size = 32; /* input size */
char input[size];
char *first,*last; /* buffers */
/* prompt for the first name */
printf("Your first name: ");
fgets(input,size,stdin);
/* allocate storage for the first name */
/* remember to add one byte for the null character! */
first = malloc( sizeof(char) * strlen(input) + 1 );
if( first==NULL )
{
fprintf(stderr,"Unable to allocate memory\n");
exit(1);
}
/* copy the string */
strcpy(first,input);
/* prompt for the last name */
printf("Your last name: ");
fgets(input,size,stdin);
/* allocate storage for the last name */
last = malloc( sizeof(char) * strlen(input) + 1 );
if( last==NULL )
{
fprintf(stderr,"Unable to allocate memory\n");
exit(1);
}
/* copy the string */
strcpy(last,input);
/* this part is optional, though useful */
printf("Hello, %s %s!\n",first,last);
/* yes, the newlines screw up the output
bonus points if you dealt with them! */
/* clean-up */
free(first);
free(last);
return 0;
}
Output
Your first name: Dan
Your last name: Gookin
Hello, Dan
Gookin
!
Notes
* The output appears on three lines because this code doesn't strip the newline from input. Remember that the fgets() function always reads and stores the newline character (\n).
* Constant integer size sets the input value, which is used throughout the source code.
* Array input[] stores input.
* Pointer variables first and last hold the addresses for buffers where the first and last names are stored.
* Storage can't be allocated until input is received. The first fgets() function reads standard input, storing it in the input[] buffer. Immediately afterwards, storage is allocated for the first pointer, setting the size to the length of input plus one for the null character at the end of the string. The strcpy() function copies the string from the input[] buffer to the freshly-allocated buffer.
* The same action happens for the last name input: Array input[] is used again, with storage allocated for pointer last based on the string length of text input.
* For both pointers, a test is made to ensure that storage was allocated.
* When all the input and allocation is done, a printf() statement outputs the results.
* The program clean-up frees both pointers, first and last.
* Bonus points for you if you removed the newlines from the fgets() function's input!
Copyright © 1997-2025 by QPBC.
All rights reserved
