Search code examples
cdata-structuresstructinitialization

How can I initialize a struct in C?


I have two struct (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;

In the main I have to initialize them.

First, I tried This:

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

And it works but I have to find another way to do this.

t_bitmapheader  filehdr;
t_bitmapinfo    infohdr;

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

P.S: I Have to initialize them in another line like in the second code.

Thank You.


Solution

  • You can use compound literals to generate anonymous structures.

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