Nested Struct



  • Hi,

    ich habe folgenden struct.

    struct icmphdr
    {
      u_int8_t type;		/* message type */
      u_int8_t code;		/* type sub-code */
      u_int16_t checksum;
      union
      {
        struct
        {
          u_int16_t	id;
          u_int16_t	sequence;
        } echo;			/* echo datagram */
        u_int32_t	gateway;	/* gateway address */
        struct
        {
          u_int16_t	__unused;
          u_int16_t	mtu;
        } frag;			/* path mtu discovery */
      } un;
    };
    

    Wie kann ich dann in der Funktion.

    void buildIcmpEchoRequest( struct icmphdr * icmphdr, 
    						   u_int16_t id, u_int16_t seq )
    

    Wie kann ich in icmphdr das echo der union un setzen? Irgendwie will er das immer nicht machen :(. Müsste ja irgendwie so sein

    icmphdr->un.echo = {id, seq};
    

    Das kompiliert er aber nicht.
    MfG Maley



  • Bei einer Zuweisung kannst du keine Initialisierungsliste verwenden, sondern mußt jedes Element einzeln ansprechen, d.h:

    icmphdr->un.echo.id = id;
    icmphdr->un.echo.sequence = seq;
    


  • Dickes Dankeschön :D. Klappt.



  • Mit entsprechender expliziter Typdeklaration

    struct icmphdr
    {
      u_int8_t type;        /* message type */
      u_int8_t code;        /* type sub-code */
      u_int16_t checksum;
      union
      {
        struct echo  /* <-- hier explizit */
        {
          u_int16_t    id;
          u_int16_t    sequence;
        } echo;            /* echo datagram */
        u_int32_t    gateway;    /* gateway address */
        struct
        {
          u_int16_t    __unused;
          u_int16_t    mtu;
        } frag;            /* path mtu discovery */
      } un;
    };
    

    geht es für C99 auch mit compound-Literalen:

    #if __STDC_VERSION__ < 199901L
    #error nur mit C99
    #endif
    ...
    icmphdr->un.echo = (struct echo){id, seq};
    

Anmelden zum Antworten