程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C >> C語言入門知識 >> C語言結構體初始化的三種方法

C語言結構體初始化的三種方法

編輯:C語言入門知識

直接上示例

 

#include 

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"
	},
};
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved