Thread: Is this a valid union definition?

  1. #1
    Registered User
    Join Date
    Sep 2015
    Posts
    22

    Post Is this a valid union definition?

    I'm trying to write a function to serialise data within a struct so I can send it over UDP by defining a union to map the struct to a byte array:

    Code:
    typedef struct scan_data_t
    {
         long range;
         float angle;
    } scan_data_t
    
    typedef union udp_packet_t
    {
        struct data_t
        {
            char command;
            int num_scans;
            scan_data_t *scans;
        } data;
        char *udp;
    } __attribute__((packed)) udp_packet_t;
    Last edited by SqueezyPeas; 12-21-2017 at 06:12 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    If you want to serialise data, then it can't contain any pointers.

    Having solved that, you would declare
    char udp[sizeof(data)]
    as your serialisation member.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Sep 2015
    Posts
    22
    Quote Originally Posted by Salem View Post
    If you want to serialise data, then it can't contain any pointers.

    Having solved that, you would declare
    char udp[sizeof(data)]
    as your serialisation member.
    Thanks. I'm rethinking the whole design with that in mind.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 05-10-2017, 06:27 AM
  2. Multiple definition error, one definition
    By frog in forum C++ Programming
    Replies: 9
    Last Post: 10-21-2010, 03:15 AM
  3. Socket file descriptor valid and then not valid
    By Florian in forum C Programming
    Replies: 3
    Last Post: 05-22-2010, 08:23 AM
  4. Is this valid?
    By Boksha in forum C++ Programming
    Replies: 2
    Last Post: 06-29-2002, 01:55 PM

Tags for this Thread