Home > Backend Development > C++ > How Are Arrays Passed to Functions in C ?

How Are Arrays Passed to Functions in C ?

DDD
Release: 2024-12-19 04:26:08
Original
986 people have browsed it

How Are Arrays Passed to Functions in C  ?

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);
Copy after login

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);
Copy after login

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";
}
Copy after login

The output of the code is as follows:

5 10 15
2 4 6 8 10
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template