Whenever we need to pass a list of elements as argument to any functions in C language, it is prefered to do so using an array
. But how can we pass an array as argument to a function? Let's see how its done.
There are two possible ways to do so, one by using call by value and other by using call by reference.
We will study the second way in details later when we will study pointers.
We don't return an array from functions, rather we return a pointer holding the base address of the array to be returned. But we must, make sure that the array exists after the function ends i.e. the array is not local to the function.
We will discuss about this when we will study pointers with arrays.
Now let's see a few examples where we will pass a single array element as argument to a function, a one dimensional array to a function and a multidimensional array to a function.
Let's write a very simple program, where we will declare and define an array of integers in our main()
function and pass one of the array element to a function, which will just print the value of the element.
4
To understand how this is done, let's write a function to find out average of all the elements of the array and print it.
We will only send in the name of the array as argument, which is nothing but the address of the starting element of the array, or we can say the starting memory address.
94.6
Here again, we will only pass the name of the array as argument.
Please enter 9 numbers for the array: 1 2 3 4 5 6 7 8 9 The complete array is: 1 2 3 4 5 6 7 8 9