易百教程

填充初始化结构体

可以在创建结构变量时赋值。首先要定义结构类型并声明一个结构变量,并预设其成员值。确保预设值与结构中定义的成员的顺序和类型一致。

示例代码

#include <stdio.h> 

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

    printf("The first president was %s\n", first.name);
    printf("He was inaugurated in %d\n", first.year);
    system("pause");
    return(0);
}

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

The first president was George Washington
He was inaugurated in 1789

还可以声明一个结构体并在一个语句中初始化它:

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