简体   繁体   English

如何通过指针访问结构成员

[英]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. 1)要通过传递指针地址来访问结构变量a,在上述函数func中。

2) In following case how it will behave example: 2)在以下情况下它将如何表现示例:

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. 这两种情况都是相同的,因为stu **pstdu *代表相同的类型。 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. 如注释中所述,在typedef中使用指针被认为是不好的做法,因为它可以掩盖指针在使用中并可能造成混淆的事实。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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