前言

为了避免遗忘,下面记录了几种常见的 C 语言结构体定义方法,方便日后回忆。

结构体顺序初始化以及乱序初始化

#include <stdio.h>  
​  
struct Book{  
    int id;  
    char* name;  
    double price;  
    char* auth;  
};  
​  
int main()  
{  
    //赋值方法 1   
    struct Book b1={  
        1,  
        "Book 1",  
        111.11,  
        "Author 1"  
    };  
      
    //赋值方法 2   
    struct Book b2;  
    b2.id=2;  
    b2.name="Book 2";  
    b2.price=222.22;  
    b2.auth="Author 2";  
      
    //赋值方法 3   
    struct Book b3={  
        .id=3,  
        .price=333.33,  
        .name="Book 3",  
        .auth="Author 3"  
    };  
      
    //赋值方法 4   
    struct Book b4={  
        id: 4,  
        price: 444.44,  
        name: "Book 4",  
        auth: "Author 4"  
    };  
      
    return 0;  
}

结构体数组初始化

    //赋值方法 5   
    struct Book b[10]={  
        [0]={  
            .id=0,  
            .price=123,  
            .name="Book 0"  
        },  
        [5]={  
            id: 5,  
            price: 555.55  
        },  
        [6]={  
            .auth="Author 6"  
        }  
    };

参考资料:

  1. C语言结构体之顺序初始化和乱序初始化 https://blog.csdn.net/zhaodong1102/article/details/122883306