representation of MAC address in C code

Discussion in 'C Programming' started by Mark, Oct 22, 2013.

  1. Mark

    Mark Guest


    I often see such representation of MAC address in C code, e.g.
    struct mac_addr {
    unsigned char bytes[6];
    }Why necessary put an array in a structure, why not just have an array? What
    benefit does this provide, other that it allows to assign a struct (and in C
    it'snot possible to assign an array)?

    Mark, Oct 22, 2013
    1. Advertisements

  2. Mark

    James Kuyper Guest

    It's also not possible to pass an array by value to a C function, or to
    return it as the value of the function; both of those are allowed for
    James Kuyper, Oct 22, 2013
    1. Advertisements

  3. Ironically, you may be best placed to say since you often see this sort
    of thing in C code -- I don't. What does the C code (in which you often
    see these things) do that could not be done as simply with an array? If
    nothing, then it's probably just for familiarity -- many people find C's
    arrays surprising and the struct wrapper removes some of the oddities.
    Ben Bacarisse, Oct 22, 2013
  4. Mark

    Les Cargill Guest

    Because then you have a "struct mac_addr" - or preferably:

    typedef struct {
    unsigned char bytes[6];
    } mac_addr;

    so the intent of the object is clearer.
    Les Cargill, Oct 22, 2013
  5. In addition to what was posted already, you gain some type safety.
    A function expecting a MAC address as a char array (instead of a
    mac_addr struct) may accept any char array as (a possibly invalid)
    Roberto Waltman, Oct 22, 2013
  6. Mark

    Lynn McGuire Guest

    And the MAC address is moving from 48 bits
    to 64 bits:

    Lynn McGuire, Oct 25, 2013
  7. Mark

    Jorgen Grahn Guest

    Also (or put differently) you lose the '6' when you don't pass by
    value. The callee must have its own knowledge of the array length,
    and sizeof won't work.

    I always make a point of wrapping fixed-size arrays in structs, so
    they behave more normally. Oddly, some libraries we use at work
    represents MACs and IPv6 addresses with typedefs like this:

    typedef uint8_t Ipv6Address_t[16];

    Don't know why, since there /are/ standard types for this already in
    the OS we use, and those standard type use structs of course.

    Anyway, we've had bugs caused by the typedef: it looks too much like
    call by value when you say 'void foo(Ipv6Address_t addr);'.

    Jorgen Grahn, Oct 27, 2013
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.