Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Arrays to Function in C++

Tags:

c++

#include <iostream> using namespace std;  void printarray (int arg[], int length) {     for (int n = 0; n < length; n++) {         cout << arg[n] << " ";         cout << "\n";     } }  int main () {      int firstarray[] = {5, 10, 15};      int secondarray[] = {2, 4, 6, 8, 10};      printarray(firstarray, 3);      printarray(secondarray, 5);       return 0; } 

This code works, but I want to understand how is the array being passed.

When a call is made to the printarray function from the main function, the name of the array is being passed. The name of the array refers to the address of the first element of the array. How does this equate to int arg[]?

like image 592
Jay K Avatar asked Jan 13 '13 22:01

Jay K


People also ask

How arrays are passed to functions in C?

To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.

What is the correct syntax for passing array to a function?

The general syntax for passing an array to a function in C++ is: FunctionName (ArrayName);

What are two ways to pass array to a function?

There are two possible ways to do so, one by using call by value and other by using call by reference.


1 Answers

The syntaxes

int[] 

and

int[X] // Where X is a compile-time positive integer 

are exactly the same as

int* 

when in a function parameter list (I left out the optional names).

Additionally, an array name decays to a pointer to the first element when passed to a function (and not passed by reference) so both int firstarray[3] and int secondarray[5] decay to int*s.

It also happens that both an array dereference and a pointer dereference with subscript syntax (subscript syntax is x[y]) yield an lvalue to the same element when you use the same index.

These three rules combine to make the code legal and work how you expect; it just passes pointers to the function, along with the length of the arrays which you cannot know after the arrays decay to pointers.

like image 183
Seth Carnegie Avatar answered Oct 24 '22 14:10

Seth Carnegie