简体   繁体   English

如何使用结构指针访问结构成员

[英]How to access structure members with structure pointers

I have following code: 我有以下代码:

#include <stdio.h>
#include <stdlib.h>
#include<string.h>

struct tag
{
    int x;
};

int main()
{
    struct tag stvar;
    struct tag*stptr=&stvar;

    *(stptr).x=9;

    return 0;
}

I could use stptr->x but not *(stptr).x . 我可以使用stptr->x但不能使用*(stptr).x I am getting request for member 'x' in 'stptr', which is of pointer type 'tag*' (maybe you meant to use '->' ?) Where am i getting it wrong? request for member 'x' in 'stptr', which is of pointer type 'tag*' (maybe you meant to use '->' ?)收到request for member 'x' in 'stptr', which is of pointer type 'tag*' (maybe you meant to use '->' ?)我在哪里弄错了? How to access member with struct pointers? 如何使用结构指针访问成员?

Change: 更改:

*(stptr).x=9;

to

(*stptr).x=9;

The first statement is equivalent to *(stptr.x)=9; 第一条语句等效于*(stptr.x)=9; as postfix operators have higher precedence than unary operators. 因为后缀运算符的优先级高于一元运算符。 Of course it is better to use the dedicated -> operator to write this statement: 当然,最好使用专用的->运算符编写以下语句:

stptr->x=9;

In general accessing structure variables can be gone in two ways 通常,可以通过两种方式访问​​结构变量

value.structure_variable; // using (.) operator

or 要么

( address or pointer )-> structure_variable // using -> operator

as ouah pointed out in the answer 正如ouah在回答中指出的

*(stptr).x=9;

is a wrong assignment, on the other hand 另一方面是错误的分配

(*stptr) is basically the value at address pointer by stptr hence translates to a value thus (* stptr)基本上是stptr在地址指针处的值,因此转换为一个值

(*stptr).x=9; 

is Valid, also since stptr is a pointer itself 是有效的,也是因为stptr本身就是一个指针

stptr->x = 9;

is harmless , safe and most popular way to assign. 是无害,安全且最受欢迎的分配方式。

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

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