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!
====Multidimensional arrays==== In addition, C supports arrays of multiple dimensions, which are stored in [[row-major order]]. Technically, C multidimensional arrays are just one-dimensional arrays whose elements are arrays. The syntax for declaring multidimensional arrays is as follows: <syntaxhighlight lang=C>int array2d[ROWS][COLUMNS];</syntaxhighlight> where ''ROWS'' and ''COLUMNS'' are constants. This defines a two-dimensional array. Reading the subscripts from left to right, ''array2d'' is an array of length ''ROWS'', each element of which is an array of ''COLUMNS'' integers. To access an integer element in this multidimensional array, one would use <syntaxhighlight lang=C>array2d[4][3]</syntaxhighlight> Again, reading from left to right, this accesses the 5th row, and the 4th element in that row. The expression {{code|array2d[4]}} is an array, which we are then subscripting with [3] to access the fourth integer. {| class="wikitable" style="margin-left: auto; margin-right: auto; text-align: center" |+ Array subscripts vs. pointer arithmetic<ref>{{cite book|last=Balagurusamy|first=E|title=Programming in ANSI C|publisher=Tata McGraw Hill|pages=366}}</ref> ! style="text-align: left" | Element ! First ! Second row, second column ! ''i''th row, ''j''th column |- ! style="text-align: left" | Array subscript | {{C-lang|array[0][0]}} | {{C-lang|array[1][1]}} | {{C-lang|array[i - 1][j - 1]}} |- ! style="text-align: left" | Dereferenced pointer | {{C-lang|*(*(array + 0) + 0)}} | {{C-lang|*(*(array + 1) + 1)}} | {{C-lang|*(*(array + i - 1) + j - 1)}} |} Higher-dimensional arrays can be declared in a similar manner. A multidimensional array should not be confused with an array of pointers to arrays (also known as an [[Iliffe vector]] or sometimes an ''array of arrays''). The former is always rectangular (all subarrays must be the same size), and occupies a contiguous region of memory. The latter is a one-dimensional array of pointers, each of which may point to the first element of a subarray in a different place in memory, and the sub-arrays do not have to be the same size. The latter can be created by multiple uses of {{code|malloc}}.
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)