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!
====Array parameters==== Function parameters of array type may at first glance appear to be an exception to C's pass-by-value rule. The following program will print 2, not 1: <syntaxhighlight lang=C> #include <stdio.h> void setArray(int array[], int index, int value) { array[index] = value; } int main(void) { int a[1] = {1}; setArray(a, 0, 2); printf ("a[0]=%d\n", a[0]); return 0; } </syntaxhighlight> However, there is a different reason for this behavior. In fact, a function parameter declared with an array type is treated like one declared to be a pointer. That is, the preceding declaration of {{code|setArray}} is equivalent to the following: <syntaxhighlight lang=C> void setArray(int *array, int index, int value) </syntaxhighlight> At the same time, C rules for the use of arrays in expressions cause the value of {{code|a}} in the call to {{code|setArray}} to be converted to a pointer to the first element of array {{code|a}}. Thus, in fact this is still an example of pass-by-value, with the caveat that it is the address of the first element of the array being passed by value, not the contents of the array. Since C99, the programmer can specify that a function takes an array of a certain size by using the keyword {{code|static}}. In <code>void setArray(int array[static 4], int index, int value)</code> the first parameter must be a pointer to the first element of an array of length at least 4. It is also possible to add qualifiers (<code>const</code>, <code>volatile</code> and <code>restrict</code>) to the pointer type that the array is converted to by putting them between the brackets.
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)