结构体的几种初始化方法

1.基本初始化

基本初始化是最常用的结构体初始化方法,通过使用“{}”括号来初始化结构体变量。例如

struct Person
{

    char name[20];

    int age;

};

struct Person p = {"John", 25};

2.指定成员初始化

指定成员初始化可以通过指定成员名来初始化结构体的成员变量。例如

struct Person
{

    char name[20];

    int age;

};

struct Person p = { .age = 25};

3.常量表达式初始化

常量表达式初始化可以在结构体定义时用常量表达式对结构体成员进行初始化。

struct Circle
{
int radius;
double area;
};

const double PI = 3.14;
struct Circle c = {5, PI * 5 * 5};

4. 定义后逐个赋值

struct InitMember
{
    int first;
    double second;
    char* third;
    float four;
};

struct InitMember test;

test.first = -10;
test.second = 3.141590;
test.third = "method two";
test.four = 0.25;

5. 定义时乱序赋值

struct InitMember
{
    int first;
    double second;
    char* third;
    float four;
};

struct InitMember test = {
	second: 3.141590,
	third: "method three",
	first: -10,
	four:0.25
};