I am currently learning C by reading a good beginner's book called "Teach Yourself C in 21 Days" (I have already learned Java and C# so I am moving at a much faster pace). I was reading the chapter on pointers and the -> (arrow) operator came up without explanation. I think that it is used to call members and functions (like the equivalent of the . (dot) operator, but for pointers instead of members). But I am not entirely sure. Could I please get an explanation and a code sample?
相关问题
- Multiple sockets for clients to connect to
- Do the Java Integer and Double objects have unnece
- What does an “empty line with semicolon” mean in C
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
I'd just add to the answers the "why?".
.
is standard member access operator that has a higher precedence than*
pointer operator.When you are trying to access a struct's internals and you wrote it as
*foo.bar
then the compiler would think to want a 'bar' element of 'foo' (which is an address in memory) and obviously that mere address does not have any members.Thus you need to ask the compiler to first dereference whith
(*foo)
and then access the member element:(*foo).bar
, which is a bit clumsy to write so the good folks have come up with a shorthand version:foo->bar
which is sort of member access by pointer operator.output is 5 5 5
a->b
is just short for(*a).b
in every way (same for functions:a->b()
is short for(*a).b()
).Dot is a dereference operator and used to connect the structure variable for a particular record of structure. Eg :
In such way we can use a dot operator to access the structure variable
Here the to access the values of
i
andj
we can use the variablea
and the pointerp
as follows:a.i
,(*p).i
andp->i
are all the same.Here
.
is a "Direct Selector" and->
is an "Indirect Selector".I had to make a small change to Jack's program to get it to run. After declaring the struct pointer pvar, point it to the address of var. I found this solution on page 242 of Stephen Kochan's Programming in C.
Run this in vim with the following command:
Will output: