Passing Arrays to Functions in C
In C , arrays can be passed to functions either by reference or by value. However, arrays are not like regular variables in that you cannot simply pass an array name to a function and have it be treated like a single element of a particular type. Instead, an array name is treated as a pointer to the first element of the array.
Therefore, when you declare a function parameter as an array, you are actually declaring a pointer to that type of element. For example, the following function declaration declares a function that takes an array of ints and an integer representing the length of the array:
void printarray(int arg[], int length);
When a call is made to the printarray function from the main function, the name of the array is being passed as an argument. The name of the array refers to the address of the first element of the array. This is equivalent to passing a pointer to the first element of the array.
In the code below, the variable firstarray is an array of three integers. The variable secondarray is an array of five integers. The printarray function is called twice, once with the firstarray argument and once with the secondarray argument. The length of the firstarray argument is 3, and the length of the secondarray argument is 5.
int firstarray[] = {5, 10, 15}; int secondarray[] = {2, 4, 6, 8, 10}; printarray(firstarray, 3); printarray(secondarray, 5);
In the printarray function, the arg parameter is a pointer to the first element of the array being passed in. The length parameter is the length of the array being passed in. The printarray function prints out the values of the array elements.
void printarray (int arg[], int length) { for (int n = 0; n < length; n++) { cout << arg[n] << " "; } cout << "\n"; }
The output of the code is as follows:
5 10 15 2 4 6 8 10
The above is the detailed content of How Are Arrays Passed to Functions in C ?. For more information, please follow other related articles on the PHP Chinese website!