Question:

Pointer to structure members inside a union: how?

by  |  earlier

0 LIKES UnLike

Hi. I've got a union, containing several structures in C like this:

======================================... {

struct bit_values

{

unsigned char b0:1;

unsigned char b1:1;

unsigned char b2:1;

unsigned char b3:1;

} b;

struct input_data

{

unsigned char gp1:1;

unsigned char gp2:1;

unsigned char gp3:1;

unsigned char gp4:1;

unsigned char gp5:1;

unsigned char gp6:1;

unsigned char gp7:1;

unsigned char gp8:1;

} in;

struct eight_bit_words

{

unsigned char A:8;

unsigned char B:8;

} eight_bit;

} un;

======================================...

I want to access the data in a variable such as

un.eight_bit.A

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?

 Tags:

   Report

2 ANSWERS


  1. 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.


  2. would this:

    eight_bit_words *your_pointer_name_here = &un.eight_bit.A;

    work?

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.