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 elements==== The primary facility for accessing the values of the elements of an array is the array subscript operator. To access the ''i''-indexed element of ''array'', the syntax would be {{code|array[i]}}, which refers to the value stored in that array element. Array subscript numbering begins at 0 (see [[Zero-based indexing]]). The largest allowed array subscript is therefore equal to the number of elements in the array minus 1. To illustrate this, consider an array ''a'' declared as having 10 elements; the first element would be {{code|a[0]}} and the last element would be {{code|a[9]}}. C provides no facility for automatic [[bounds checking]] for array usage. Though logically the last subscript in an array of 10 elements would be 9, subscripts 10, 11, and so forth could accidentally be specified, with undefined results. Due to arrays and pointers being interchangeable, the addresses of each of the array elements can be expressed in equivalent [[pointer arithmetic]]. The following table illustrates both methods for the existing array: {| class="wikitable" style="margin-left: auto; margin-right: auto; text-align: center" |+ Array subscripts vs. pointer arithmetic ! style="text-align: left" | Element ! First ! Second ! Third ! ''n''th |- ! style="text-align: left" | Array subscript | {{C-lang|array[0]}} | {{C-lang|array[1]}} | {{C-lang|array[2]}} | {{C-lang|array[n - 1]}} |- ! style="text-align: left" | Dereferenced pointer | {{C-lang|*array}} | {{C-lang|*(array + 1)}} | {{C-lang|*(array + 2)}} | {{C-lang|*(array + n - 1)}} |} Since the expression {{code|a[i]}} is semantically equivalent to {{code|*(a+i)}}, which in turn is equivalent to {{code|*(i+a)}}, the expression can also be written as {{code|i[a]}}, although this form is rarely used.
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)