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

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

定义时赋值

1
2
3
4
5
6
7
8
9
struct InitMember
{
    int first;
    double second;
    char* third;
    float four;
};

struct InitMember test = {-10,3.141590,"method one",0.25};

需要注意对应的顺序,不能错位。

定义后逐个赋值

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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;

因为是逐个确定的赋值,无所谓顺序啦。

定义时乱序赋值(C风格)

这种方法类似于第一种方法和第二种方法的结合体,既能初始化时赋值,也可以不考虑顺序;

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
struct InitMember
{
    int first;
    double second;
    char* third;
    float four;
};

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

这种方法经常使用,是很不错的一种方式。

定义时乱序赋值(C++风格)

这种方法和前一种类似,网上称之为C++风格,类似于key-value键值对的方式,同样不考虑顺序。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
struct InitMember
{
    int first;
    double second;
    char* third;
    float four;
};

struct InitMember test = {
    second:3.141590,
    third:"method three",
    first:-10,
    four:0.25
};
记录并分享
Built with Hugo
主题 StackJimmy 设计