当前位置:网站首页 > 技术博客 > 正文

结构体如何初始化赋值

C语言

结构体初始化

有以下

四种 方法

1. 按顺序

初始化

:按照结构体定义中的成员顺序依次给每个成员赋值。

例如:

```c

struct

Student {

int id;

char name[20];

int age;

};

int main() {

struct

Student s = {1, "Tom", 18};

return 0;

}

  2. 指定成员 初始化 :通过成员名字指定对应的值进行 初始化  例如: ```c  struct Student { int id; char name[20]; int age; };  int main() {  struct Student s = {.id=1, .name="Tom", .age=18}; return 0; } 

3. 省略成员

初始化

:如果在

初始化

时只给部分成员赋值,其他未赋值的成员会被自动

初始化

为0或者空。

例如:

```c

struct

Student {

int id;

char name[20];

int age;

};

int main() {

struct

Student s = {.id=1};

return 0;

}

  4. 嵌套 结构体初始化 :如果结构体中的成员是其他结构体类型,可以使用以上任何一种方式 初始化 嵌套结构体。 例如: ```c  struct Address { char city[20]; char street[20]; };   struct Student { int id; char name[20]; int age;  struct Address address; };  int main() {  struct Student s = {.id=1, .name="Tom", .age=18, .address={.city="Beijing", .street="Main Street"}}; return 0; } 

以上是C语言

结构体初始化

四种

常用

方法

版权声明


相关文章:

  • office破解教程2024-12-20 08:30:04
  • linux最常用命令2024-12-20 08:30:04
  • java内存模型的三大特性2024-12-20 08:30:04
  • mipi接口应用2024-12-20 08:30:04
  • fastjson trim2024-12-20 08:30:04
  • juc并发编程与源码分析2024-12-20 08:30:04
  • scrum实例2024-12-20 08:30:04
  • 我的世界宝可梦指令表20202024-12-20 08:30:04
  • 开窗函数 rows between2024-12-20 08:30:04
  • 弹性盒子常用属性2024-12-20 08:30:04