温馨提示×

C语言结构体数组如何初始化赋值

小亿
289
2023-12-28 00:16:17
栏目: 编程语言
C语言开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

C语言结构体数组的初始化赋值可以通过以下两种方式进行:

  1. 逐个赋值:可以使用逐个赋值的方式给结构体数组的每个元素进行赋值,例如:
struct Student {
    char name[20];
    int age;
};

int main() {
    struct Student students[3];
    
    strcpy(students[0].name, "Tom");
    students[0].age = 18;
    
    strcpy(students[1].name, "Alice");
    students[1].age = 20;
    
    strcpy(students[2].name, "Bob");
    students[2].age = 19;
    
    return 0;
}
  1. 使用初始化列表:可以使用初始化列表的方式对结构体数组进行初始化赋值,例如:
struct Student {
    char name[20];
    int age;
};

int main() {
    struct Student students[3] = {
        {"Tom", 18},
        {"Alice", 20},
        {"Bob", 19}
    };
    
    return 0;
}

通过上述两种方式,可以对C语言中的结构体数组进行初始化赋值。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:c语言结构体数组怎么初始化

0