Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
C syntax
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
====Accessing members==== Members are accessed using the name of the instance of a structure or union, a period ({{code|.}}), and the name of the member. For example, given the declaration of ''tee'' from above, the member known as ''y'' (of type {{code|float}}) can be accessed using the following syntax: <syntaxhighlight lang=C>tee.y</syntaxhighlight> Structures are commonly accessed through pointers. Consider the following example that defines a pointer to ''tee'', known as ''ptr_to_tee'': <syntaxhighlight lang=C>struct s *ptr_to_tee = &tee;</syntaxhighlight> Member ''y'' of ''tee'' can then be accessed by dereferencing ''ptr_to_tee'' and using the result as the left operand: <syntaxhighlight lang=C>(*ptr_to_tee).y</syntaxhighlight> Which is identical to the simpler {{code|tee.y}} above as long as ''ptr_to_tee'' points to ''tee''. Due to [[Operators in C and C++#Operator precedence|operator precedence]] ("." being higher than "*"), the shorter <code>*ptr_to_tee.y</code> is incorrect for this purpose, instead being parsed as <code>*(ptr_to_tee.y)</code> and thus the parentheses are necessary. Because this operation is common, C provides an [[syntactic sugar|abbreviated syntax]] for accessing a member directly from a pointer. With this syntax, the name of the instance is replaced with the name of the pointer and the period is replaced with the character sequence {{code|->}}. Thus, the following method of accessing ''y'' is identical to the previous two: <syntaxhighlight lang=C>ptr_to_tee->y</syntaxhighlight> Members of unions are accessed in the same way. This can be chained; for example, in a linked list, one may refer to <code>n->next->next</code> for the second following node (assuming that <code>n->next</code> is not null).
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)