Solution for Exercise 14-5

ex1405

#include <stdio.h>

int main()
{
    struct president
    {
        char name[40];
        int year;
    } first = {
        "George Washington",
        1789
    };
   struct president second = {
        "John Adams",
        1797
    };

    printf("The first president was %s\n",first.name);
    printf("He was inaugurated in %d\n",first.year);
    printf("The second president was %s\n",second.name);
    printf("He was inaugurated in %d\n",second.year);

    return(0);
}

Notes

* I was incorrect when I wrote in the book that you cannot initialize two structures variables similar to the way first is initialized at Line 9. The second structure variable can be added as long as it's separated from the first by a comma.

* Here is how to declare both structures:

    struct president
    {
        char name[40];
        int year;
    } first = {
        "George Washington",
        1789
    }, second = {
        "John Adams",
        1797
    };

Another way to format this type of declaration is as follows, which also makes it easier to see what's going on:

    struct president
    {
        char name[40];
        int year;
    } first = { "George Washington", 1789 },
      second = { "John Adams", 1797 };

* The comma is what makes the multi-declarations happen. The data in the braces must match in quantity and type the members of the structure.

* The following code shows yet another method you can use to declare a bunch of structures, in this case as an array:

#include <stdio.h>

int main()
{
    struct president
    {
        char name[40];
        int year;
    } preslist[] = {
        "George Washington",1789,
        "John Adams", 1797
    };

    printf("The first president of the USA was %s\n",preslist[0].name);
    printf("He was inaugurated in the year %d\n",preslist[0].year);
    printf("The second president of the USA was %s\n",preslist[1].name);
    printf("He was inaugurated in the year %d\n",preslist[1].year);

    return(0);
}

* Above, the preslist[] array is declared at the end of the president structure declaration at Line 9. Then the array is defined one element at a time.

* The members must be referenced by using the array name, element number, then a dot and the member name. That format is shown in the printf() statements, Lines 14 through 17.

* This type of array declaration might cause a compiler warning. That warning can be addressed by enclosing each structure element of the array in braces, as follows:

struct president
    {
        char name[40];
        int year;
    } preslist[] = {
        { "George Washington",1789 },
        { "John Adams", 1797 }
    };