#include <stdio.h> static struct id_mesg{ char *name; unsigned int age; char *job; }; static struct id_mesg persons[] = { {"bimax", 23, "hero"}, {"deadpool", 34, "marvel"}, {"thor", 65535, "god"}, {.name = "linus", .job = "linuxman"} }; static struct id_mesg per_one = { .name = "gates", .age = 43, .job = "ITman", }; int main(int argc, char **argv) { int i; for(i = 0; i < 4; i ++) { printf("name: %s\t age: %d\t job: %s\n", persons[i].name, persons[i].age, persons[i].job); } printf("name: %s\t age: %d\t job: %s\n", per_one.name, per_one.age, per_one.job); }
程序如上所示。
static struct id_mesg persons[] = { {"bimax", 23, "hero"}, {"deadpool", 34, "marvel"}, {"thor", 65535, "god"}, {.name = "linus", .job = "linuxman"} };该段的前三个为结构体赋值常用方法,最后一个是来自C99标准,表示指定初始化,使用前缀.加变量名称进行定向赋值
static struct id_mesg per_one = { .name = "gates", .age = 43, .job = "ITman", };
上述程序运行之后的结果是:
name: bimax age: 23 job: hero