Reputation: 317
There are a number of threads on this subject, some of which have been helpful, but I need some specific help.
Say we have this code:
typedef struct A {
int b;
struct other* c;
} A_t;
struct other {
int d;
}
So, we've got a struct called A, containing an int (called b) and a pointer to a struct of type "other", called c.
Now say that later on we have:
A* pA;
which we assume points to a properly allocated instance of A.
My first question is, how do I access "d"? I've tried:
int z = (*pA).(*c).d;
but I get a compile error about expecting an identifier before the '(' token.
My second question is, what's the difference between referring to the data type as A vs. A_t? In other words, we define the struct as type A, but there's the "A_t" part at the end of the definition. I've gotten lots of vague descriptions of what it is, but I don't get it, it seems like we've just randomly decided to call the same data type by two different names, for fun.
Side note, the code above isn't straight from my project, so I can't guarantee it'll produce the same problems I've encountered. It's an assignment and I wanted to avoid posting my actual code, so I just wrote something simpler but similar.
I appreciate it!
Upvotes: 0
Views: 102
Reputation: 126175
Basic rules:
*
to dereference a pointer and postfix-.
to access a field.So taking those into account, you start with your pointer pA
. You want to dereference it to get the struct:
*pA
Then you want to get the c
field, which will require parens around what you already have:
(*pA).c
Now dereference that to get the other
object:
*(*pA).c
and then get the d
field, which requires parenthesis again:
(*(*pA).c).d
This task of "dereference and then get a field" is so common that there's a short-cut postfix operator ->
to do it in one step and avoid the parentheses. First deref pA and get c:
pA->c
then deref again and get d
pA->c->d
Upvotes: 4
Reputation: 14619
what's the difference between referring to the data type as A vs. A_t? ... decided to call the same data type by two different names, for fun
struct A
is aliased to A_t
. For "fun" or usually just convenience of having a simpler way to refer to the data type.
This is a conventional way to dereference members:
int z = pA->c->d;
From C99 §6.5.2.3:
The first operand of the -> operator shall have type ''pointer to qualified or unqualified
structure'' or ''pointer to qualified or unqualified union'', and the second operand shall
name a member of the type pointed to.
Upvotes: 3