Passing Arrays

Pass

Function Call

Function

Prototype

What it passed ?

array elements 

int g[5];

findMin(g[2],g[4]);

findMin(int g1,int g2);

findMin(int ,int );

 copy of the passed value (pass by value)

complete array

 average (g); // NO []

average (int g[]);   OR

average (int g[5]);

average (int g);//WRONG

average (int []);  OR

average (int g[]);

 actual array   (pointer to the array , address of the first element in the array.)(pass by reference).

2 dim array

int t[3][4];

 calc (t) ;

calc (t[][4]);        OR

calc (t[3][4]);

calc (t[][]);     //WRONG

calc (int t[][4]);   OR

calc (int t[3][4]);

calc (t[][]) //WRONG

 

 

Address

 

The name of an array is the same as the address of the array's first element.

#include <stdio.h>

int main()
{
char array[ 5 ];

printf
( " array = %p\n&array[0] = %p\n"
" &array = %p\n",
array, &array[ 0 ], &array );
return 0;
}

Output:

      array = 0012FF64

&array[0] = 0012FF64

   &array = 0012FF64

 

 

 

Why when we pass a complete array , the actual array is being passed not a copy of it  ?

Because in large arrays making duplicate copies of the array for each function call would :

  1. Waste computer storage.

  2. Consume execution time.

const

#include <stdio.h>

void tryToModifyArray( const int [] );

int main()
{
int a[] = { 10, 20, 30 };

tryToModifyArray( a );
printf("%d %d %d\n", a[ 0 ], a[ 1 ], a[ 2 ] );
return 0;
}

void tryToModifyArray( const int b[] )
{
b[ 0 ] /= 2; /* error */
b[ 1 ] /= 2; /* error */
b[ 2 ] /= 2; /* error */
}