简体   繁体   中英

How to access struct member via pointer to pointer

typedef struct {
    int a;
} stu, *pstdu;

void func(stu **pst);

int main() {
    stu *pst;
    pst = (stu*)malloc(sizeof(stu));
    pst->a = 10;
    func(&pst);
}

void func(stu **pstu) {
    /* how to access the variable a */
}

1) Want to access the structure variable a by passing the pointer address, in above function func.

2) In following case how it will behave example:

typedef struct {
    int a;
} stu, *pstdu;

void func(pstdu *pst);

int main() {
    stu *pst;
    pst = (stu*)malloc(sizeof(stu));
    pst->a = 10;
    func(&pst);
}

void func(pstdu *pstu) {
   /* how to access the variable a */
}

You need to dereference the first pointer, then use the pointer-to-member operator:

(*pstu)->a

The parenthesis are required because the pointer-to-member operator has higher precedence than the dereference operator.

This is the same for both cases because stu ** and pstdu * represent the same type. As mentioned in the comments, it's considered bad practice to have a pointer in a typedef because it can hide that fact that a pointer is in use and can become confusing.

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