CodesandTutorials
Next generation website theme is here (black, neon and white color) - Reduces eye strain and headache problems.
You are here - Home > Programming > C > Basics

Passing Entire Array


Description

To pass entire array to the function, we need to pass two arguments. First is the address of starting array index or array name and second is the size of array value.

In the below source code we have used function as display(&arr[0],10); which passes the address of starting array index and the number of elements in the array. Same function can be also written as display(arr,10);.

Source code

  • //Passing entire array to function and printing the elements
  • #include <stdio.h>
  • #include <conio.h>
  • void main()
  • {
  • int arr[]={34,342,5,2,35,623,32,33,4,64};
  • clrscr();
  • display(&arr[0],10);
  • getch();
  • }
  • display(int *j, int n)
  • {
  • for(int i=0;i<n;i++)
  • {
  • printf("%d\n",*j);
  • j++;
  • }
  • return 0;
  • }

Program working steps

  • First line is the comment, 2nd & 3rd lines are preprocessor directives and 5th line void main() function from where the program execution starts.
  • Array declaration and intializaton of array arr with ten elements in it.
  • clrscr to clear the screen.
  • Caller function display(&arr[0],10); calls the function definition by passing the address location number of starting array index and the value of size array arr.
  • Now the program controls moves to line no.12 where pointer variable int *j is declared to store the address of starting array element and int n to store the size of array elements.
  • Starting address is pass to know from which address it is to be processed and size of array to know when to stop.
  • In display function block code we have used for loop to print value of each array element using printf statement, which prints the value at the address location specified in *j pointer. And at each loop the value of address location is increment by one using j++; statement.
  • After terminating the for loop, function returns nothing and program control moves to line no.10 where it exits the program using getch() function.

Tip Box

Address value of zeroth index in a array is called as base address.


Advertisement





Terms of Use | Privacy Policy | Contact Us | Advertise
CodesandTutorials © 2014 All Rights Reserved