c - 如何在 C 中初始化结构?

标签 c data-structures struct initialization

我有两个结构(typedef)。

typedef struct      s_bitmapheader
{
    uint16_t bfType;
    uint32_t bfSize;
    uint16_t bfReserved1;
    uint16_t bfReserved2;
    uint32_t bfOffBits;
}                   t_bitmapheader;

typedef struct      s_bitmapinfo
{
    uint32_t bisize;
    int32_t  biwidth;
    int32_t  biheight;
    uint16_t biplanes;
    uint16_t bibitcount;
    uint32_t bicompression;
    uint32_t bisizeimage;
    int32_t  biXpelspermeter;
    int32_t  biYpelspermeter;
    uint32_t biclrused;
    uint32_t biclrimportant;
}                   t_bitmapinfo;

主要是我必须初始化它们。

首先,我尝试了这个:

t_bitmapheader  filehdr = { 0 };
t_bitmapinfo    infohdr = { 0 };

它有效,但我必须找到另一种方法来做到这一点。

t_bitmapheader  filehdr;
t_bitmapinfo    infohdr;

filehdr = { 0 };
infohdr = { 0 };

P.S:我必须像在第二个代码中那样在另一行中初始化它们。

谢谢。

最佳答案

您可以使用 compound literals生成匿名结构。

t_bitmapheader  filehdr;
t_bitmapinfo    infohdr;

filehdr = (t_bitmapheader){ 0 };
infohdr = (t_bitmapinfo){ 0 };

关于c - 如何在 C 中初始化结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64401378/

相关文章:

c - MPI_Reduce 不将结果传输到根进程

c - 尝试构建 Com0Com - c0clog.h 缺少文件

c - 如何检查嵌套结构的 malloc 结果?在C中

algorithm - 关于散列 - 二次探测证明

c# - 为什么结构比类慢?

c++ - 我需要创建一个非常大的位/ bool 值数组。我将如何在 C/C++ 中执行此操作?

algorithm - 如何证明完全二叉堆(min-heap)中第k小元素的期望深度为O(logk)?

swift - 访问结构属性

c - 在链表C程序中添加一个元素到末尾

c++ - 为新结构重载 operator()