Solution for Exercise 07_03-pmember3.c

07_03-pmember3.c

#include <stdio.h>
#include <stdlib.h>

int main()
{
	struct human {
		char *name;
		int *age;
	} person;

	/* allocate the pointers */
	person.age = malloc( sizeof(int) * 1 );
	person.name = malloc( sizeof(char) * 32 );
	if( person.name==NULL || person.age==NULL )
	{
		fprintf(stderr,"Allocation failed\n");
		exit(1);
	}

	/* assign data */
	printf("Your name: ");
	fgets(person.name,32,stdin);
	printf("Your age: ");
	scanf("%d",person.age);

	/* report data */
	printf("%s is %d years old\n",
			person.name,
			*person.age
		  );

	/* clean-up */
	free(person.name);
	free(person.age);
	return 0;
}

Output

Your name: Danny Gookin
Your age: 28
Danny Gookin
is 28 years old

Notes

* Both members of the human structure are declared as pointers: name and age

* Storage is allocated for both pointers based on the sizes they require: One integer for person.age, and 32 characters for string person.name

* A single if statement checks the return values for both pointers. If either one fails (is equal to NULL), the program quits.

* The pointers are used in this code the same as in the first two source code files from Chapter 7 in the book.

* The only time the * (dereferencing) operator is required is in the printf() statement where the value of person.age is output.

* Both pointer members are freed before the program ends.

* As with other solutions, if you wrote extra code to eliminate the newline retained by the fgets() function, you get special bonus points.