Array and function

How array is passed to function

As we have learned in the previous article array name contains the base address of an array. In this article we will learn how to pass an array in a function.

To pass the array in a function pass the name of the array and the size of the array. As the name of the array contains the base address of array which informs function where to start and size of the array tells function where to stop accessing an array.

The following example demonstrate the above fact.

Calculate square of an array elements using function

#include

void sqr(int arr[],int n) {
	int i;
	for(i = 0; i < n; i++) {
		arr[i] = arr[i] * arr[i];
	}	
}
int main() {
	int arr[20];
	int i,n;

	printf("Enter how many elements, (max-20): ");
	scanf("%d",&n);

	//Array input
	for(i = 0; i < n; i++) {
		printf("Enter element %d: ",i+1);
		scanf("%d",&arr[i]);
	}
	
	sqr(arr,n); //pass array to function		
	
	printf("After squaring each element array elements are...\n");
	for(i = 0; i < n; i++) {
		printf("%d ",arr[i]);
	}
	
	return 0;
}

Output

Enter how many elements, (max-20): 5
Enter element 1: 1
Enter element 2: 2
Enter element 3: 3
Enter element 4: 4
Enter element 5: 5
After squaring each element array elements are...
1 4 9 16 25

Explanation

As shown in the above code snippet, an array address is received by an array. So as it is clear in the previous article an array is also a type of pointer so it can hold the address of an array.

Now if you are thinking how array values are changed by function without a call by reference. So an array in a function call is treated as call by reference. To understand this fact observe the following code snippets.

void sqr(int arr[],int n) {
	int i;
	for(i = 0; i < n; i++) {
		*(arr + i) = *(arr + i) * *(arr + i);
	}	
}

As shown in the above code snippet arr[i] can be written as *(arr + i) which meaning is access value at (arr + i) address and update in the value after square on the same address. So it is able to update the array value.

Similarly, the above code snippet can be written with the help of pointers as shown below...

void sqr(int *p,int n) {
	int i;
	for(i = 0; i < n; i++) {
		*p = *p * *p;
		p++;
	}	
}

As shown in the above example, an array address is received by a pointer and each value is access by dereferencing the pointer and move the pointer to the next element by increment the pointer.

In the above code snippet initially, the pointer points the first element and shift to the next element in each iteration.

void sqr(int *p,int n) {
	int i;
	for(i = 0; i < n; i++) {
		*(p + i) = *(p + i) * *(p + i);
	}	
}

Another way to access the ith element of an array by adding i to the base address. In this case, pointer always stay at the base address to access the next elements by adding i.