暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

C语言结构体初始化的三种方法

进击的代码 2021-05-31
1330

示例

#include <stdio.h>

struct student_st
{

char c;
int score;
const char *name;
};

static void show_student(struct student_st *stu)
{
printf("c = %c, score = %d, name = %s\n", stu->c, stu->score, stu->name);
}

int main(void)
{
// method 1: 按照成员声明的顺序初始化
struct student_st s1 = {'A', 91, "Alan"};
show_student(&s1);

// method 2: 指定初始化,成员顺序可以不定,Linux 内核多采用此方式
struct student_st s2 =
{

.name = "YunYun",
.c = 'B',
.score = 92,
};
show_student(&s2);

// method 3: 指定初始化,成员顺序可以不定
struct student_st s3 =
{

c: 'C',
score: 93,
name: "Wood",
};
show_student(&s3);

return 0;
}

运行结果

初始化数组

可采用 {{ }, { }, { }} 方式,如

struct student_st stus[2] = 
{

{
.c = 'D',
.score = 94,
/*也可以只初始化部分成员*/
},
{
.c = 'D',
.score = 94,
.name = "Xxx"
},
};

文章转载自进击的代码,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论