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

一、介绍
结构体作为数据结构的基础,经常使用,其中初始化也有几种方法,这里详细介绍

二、常规初始化(先定义再初始化)

typedef struct {
    int bandrate;
    int databits;
    int stopbits;
    int parity;
    int dtr;
}serial_hard_config_def;

serial_hard_config_def serial;
serial.bandrate = 115200;
serial.databits = 8;
serial.stopbits = 1;
serial.parity = 0;
serial.dtr = 0;

三、定义的同时初始化
1、顺序初始化

typedef struct {
    int bandrate;
    int databits;
    int stopbits;
    int parity;
    int dtr;
}serial_hard_config_def;

serial_hard_config_def serial = {
	115200,
	8,
	1,
	0,
	0
};

2、乱序初始化

typedef struct {
    int bandrate;
    int databits;
    int stopbits;
    int parity;
    int dtr;
}serial_hard_config_def;

serial_hard_config_def serial = {
	.dtr = 0,
	.bandrate = 115200,
	.databits = 8,
	.stopbits = 1,
	.parity = 0,
};

3、结构体数组初始化

typedef struct {
    int bandrate;
    int databits;
    int stopbits;
    int parity;
    int dtr;
}serial_hard_config_def;

serial_hard_config_def serial[2] = {
	[0] = {
		.dtr = 0,
		.bandrate = 115200,
		.databits = 8,
		.stopbits = 1,
		.parity = 0,
		},
	[1] = {
		.dtr = 0,
		.bandrate = 115200,
		.databits = 8,
		.stopbits = 1,
		.parity = 0,
	}
};

4、嵌套结构体初始化

typedef struct {
    int bandrate;
    int databits;
    int stopbits;
    int parity;
    int dtr;
}serial_hard_config_def;

typedef struct {
    serial_hard_config_def hardware;
    int model;
 
}serial_config_def;

serial_config_def serial_config = {
	{
		.dtr = 0,
		.bandrate = 115200,
		.databits = 8,
		.stopbits = 1,
		.parity = 0,
	},
	.model = 1
}

5、嵌套结构体数组初始化

typedef struct {
    int bandrate;
    int databits;
    int stopbits;
    int parity;
    int dtr;
}serial_hard_config_def;

typedef struct {
    serial_hard_config_def hardware;
    int model;
 
}serial_config_def;

serial_config_def serial_config[2] = {
	[0] = {
			{
				.dtr = 0,
				.bandrate = 115200,
				.databits = 8,
				.stopbits = 1,
				.parity = 0,
			},
			.model = 1,
		},
	[1] = {
			{
				.dtr = 0,
				.bandrate = 115200,
				.databits = 8,
				.stopbits = 1,
				.parity = 0,
			},
			.model = 1,
		}	
}

你可能感兴趣的:(C语言,数据结构,c语言,结构体初始化,结构体)