0
struct sample
{
    int a;
    char b;
    float c;
    int *al;
    union un
    {
        int a;
        char c;
        float f;
    }*ptr;
}test;

How do I access the structure member 'al' and the union members a,c,f?

Arun
  • 45
  • 1
  • 5

2 Answers2

3

No difference than others:

  1. access al

    test.al
    

    If you want the value of al, you could get it by *(test.al).

  2. access a, c, f

    test.ptr->a;
    test.ptr->c;
    test.ptr->f;
    
Lee Duhem
  • 14,695
  • 3
  • 29
  • 47
0

The thing is that you need to dereference the pointer.

Normally we would do this to dereference the union.

test.*ptr.a.

The problem with this is that the compiler will execute the dotnotation before the dereferencing symbol, The compiler will therefore dereference the field in the union, instead of the union it self.

To solve this issue we can put ´*ptr´in parentheses to force deferencing the union before accesing the field. Like this.

test.(*ptr).a

For an easier syntax this can also be written as

test.ptr->a

Mads Gadeberg
  • 1,429
  • 3
  • 20
  • 30