易百教程

编写程序来初始化两个结构

编写程序来初始化两个结构,参考以下示例代码:

#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);

    system("pause");
    return(0);
}

执行上面示例代码,得到以下结果:

The first president was George Washington
He was inaugurated in 1789
The second president was John Adams
He was inaugurated in 1797

以下代码是用于声明两个结构:

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

格式化此类声明的另一种方法如下,这也使得代码更容易清晰:

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