简体   繁体   中英

How do I access a pointer member inside a structure in C?

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?

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; 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM