Pointer to structure members inside a union: how?

Discussion in 'Code Forum' started by aaaaaaaaaaaaaaaaaaab, Aug 25, 2008.

  1. Hi. I've got a union, containing several structures in C like this<br />
    ===================================================union {<br />
    struct bit_values<br />
    {<br />
    unsigned char b01;<br />
    unsigned char b11;<br />
    unsigned char b21;<br />
    unsigned char b31;<br />
    } b; <br />
    struct input_data<br />
    {<br />
    unsigned char gp11;<br />
    unsigned char gp21;<br />
    unsigned char gp31;<br />
    unsigned char gp41;<br />
    unsigned char gp51;<br />
    unsigned char gp61;<br />
    unsigned char gp71;<br />
    unsigned char gp81;<br />
    } in;<br />
    <br />
    struct eight_bit_words<br />
    {<br />
    unsigned char A8;<br />
    unsigned char B8;<br />
    } eight_bit;<br />
    } un;<br />
    ===================================================<br />
    <br />
    I want to access the data in a variable such as <br />
    un.eight_bit.A<br />
    from an external function, preferably without passing the entire union. Dev C++ refuses to give me an address to a union member, so does anyone know how?<br />
    <br />
    nah, apparently not.<br />
    <br />
    same issue the compiler reports<br />
    "cannot take address of bit-field 'A'
  2. peepoohead7

    peepoohead7 New Member

    would this

    eight_bit_words *your_pointer_name_here = &un.eight_bit.A;

  3. satsumo

    satsumo New Member

    The compiler is correct. A pointer can only adress at a byte, this is implicit in the nature of computer. You can't point at the 4 bit of a byte.

    The simplest way to do this is to pass the address of the whole struct and refer to the bits yourself.

    In your third example (eight_bit_words), you don't need the bit size at all. Unsigned char's are 8 bits wide anyway. If you don't specify the bit size the compiler won't consider it a bit field and you will be able to get a pointer to it.

    Depending on what you're trying to do, you could just keep your data in a short (no struct or union) and pass a bit mask into the function, to access the bits you want.

    Otherwise, read the value you want into a char (or int) and pass that to the function. Though its not elegant, it does the job.

Share This Page