C Tutorial
Array elements are always stored in continuous memory locations.
This C program passes the entire array to the function instead of individual elements in the array.
Array can be passed to the function using the address of the first element of the array.
Address of first element is accessed using any of the below statement.
&array_name[0] or array_name
#include<stdio.h> int sum(int*, int); void main() { int total = 0; int numbers[] = {10, 20, 30, 40, 50}; total = sum(&numbers[0], 5); printf("Sum: %d", total); } int sum(int *num, int n) { int total = 0, i = 1; while(i<=n) { printf("Element %d: %d\n", i, *num); total += *num; num++; i++; } return total; }Output:
$ cc passing-array-to-function.c $ ./a.out Element 1: 10 Element 2: 20 Element 3: 30 Element 4: 40 Element 5: 50 Sum: 150
#include<stdio.h> int sum(int*, int); void main() { int total = 0; int numbers[] = {10, 20, 30, 40, 50}; total = sum(numbers, 5); printf("Sum: %d", total); } int sum(int *num, int n) { int total = 0, i = 1; while(i<=n) { printf("Element %d: %d\n", i, *num); total += *num; num++; i++; } return total; }Outptu:
$ cc passing-array-to-function.c $ ./a.out Element 1: 10 Element 2: 20 Element 3: 30 Element 4: 40 Element 5: 50 Sum: 150
C Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us
| Report website issues in Github
| Facebook page
| Google+ page