Search code examples
c++structinitializationmemset

(Struct *) Initialization using attribute value name?


I have defined this struct:

typedef struct WHEATHER_STRUCT
{
   unsigned char packetID[1];
   unsigned char packetSize[2];
   unsigned char subPacketID[1];
   unsigned char subPacketOffset[2];
   ...
} wheather_struct;

How can I initialize this struct (using constructor or new) accessing by an attribute name? For example:

wheather_struct.packetID = 1;

Finally

I tried this solution and it works for me, but do you think it is a good choice?

WHEATHER_STRUCT * wheather_struct = new WHEATHER_STRUCT();
*weather_struct->packetID = '1';

And for a float attribute:

wheather_struct->floatAttribute= 111.111

Solution

  • In C++ you can use new to allocate and initialize:

    wheather_struct *p = new wheather_struct();
    

    Note the parenthesis at the end - this is value initialization - fills members of built-in types with 0.

    And then:

    p->packetID[0] = 1;