Pass an entire array to a function using Pointers

How to pass an entire array to a function using Pointers

It is not possible to directly pass array to a function but we can use pointers for this purpose. Pointers allows us to pass an entire array to a function. And here we show how this is done.

Consider we have an array call arr with 5 elements.

Consider that we want to calculate the sum of the 5 elements. For this we create a new function call sum() that calculates the sum and returns the sum. For this we have to pass the array elements to the sum() function. To do this we can use pointers. The following code shows the example of this.

In the sum() function we receive the address of the first element of the array in pointer variable j. We also pass the number of elements in the array as 2nd argument to the function sum. Then using the for loop we calculate the temporary sum for the first element, increment the address to get the next element value and then calculate the temporary sum again. At the end, we return the calculated temporary sum. The returned sum is assigned to the variable s which is then display in the output.

This is an example of function call by reference. See difference between function call by value and call by reference for more information on this.

What do you think?

17 points
Upvote Downvote

Total votes: 0

Upvotes: 0

Upvotes percentage: 0.000000%

Downvotes: 0

Downvotes percentage: 0.000000%

Leave a Reply

Your email address will not be published. Required fields are marked *

Printing Array values using pointers

USART read write tutorial using MPLAB Harmony

USART read write tutorial using MPLAB Harmony