Passing Array to Function in C
In C, there are various problems which requires passing more than one variable of same type to a function. Consider a function which sorts the 10 elements in ascending order. Here, instead of declaring 10 different numbers and then passing into the function, we can declare and initialize an array and pass that into the function.
Methods to declare a function that receives an array as an argument
There are three ways to declare the function which is intended to receive an array as an argument.
First way :
return_type function(type array_name[])
Declaring blank subscript notation [] is the widely used technique.
Second Way :
return_type function(type array_name[SIZE])
Optionally, we can define size in subscript notation [].
Third way :
return_type function(type *array_name)
We can also use the concept of a pointer.
Note: We can't declare a 2-D array using the first way. While declaring a 2-D array we need to define the size of array.
#include <stdio.h>
int minarray(int arr[], int size){
int min = arr[0];
int i = 0;
for (i = 1; i < size; i++){
if (min > arr[i]){
min = arr[i];
}
}
return min;
}
int main()
{
int i = 0, min = 0;
int numbers[] = {4, 5 ,7 ,3 ,8, 9};
min = minarray(numbers, 6);
printf("Minimum number is %d.\n", min);
return 0;
}
Output :
Minimum number is 3.
C function to sort the array
#include <stdio.h>
int Bubble_Sort(int a[]){
int x, y, temp;
for (x = 0; x < 10; x++){
for (y = x+1; y < 10; y++){
if (a[y] < a[x]){
temp = a[x];
a[x] = a[y];
a[y] = temp;
}
}
}
printf("Printing Sorted Elements List ....\n");
for (x = 0; x < 10; x++){
printf("%d\n", a[x]);
}
}
int main()
{
int arr[10] = {10, 9, 7, 101, 23, 44 ,12, 78, 34 ,23};
Bubble_Sort(arr);
return 0;
}
Output :
Printing Sorted Elements List ....
7
9
10
12
23
23
34
44
78
101
Returning array from the function
As we know that, a function can not return more than one value. However, if we try to write the return statement as return a, b, c; to return three values (a, b, c), the function will return the last mentioned value which is c in this case. In such cases, an array is returned from the function.
Returning an array is similar to passing the array into the function. The name of the array is returned from the function.
To store the array returned from the function, we can define a pointer which points to that array. We can traverse the array by increasing that pointer since pointer initially points to the base address of the array.
#include <stdio.h>
int *bubble_sort(int b[]){
int p, q, temp1;
for (p = 0; p < 10; p++){
for (q = p+1; q < 10; q++){
if (b[q] < b[p]){
temp1 = b[p];
b[p] = b[q];
b[q] = temp1;
}
}
}
return b;
}
int main()
{
int *g = bubble_sort(arr), p;
printf("Printing Sorted Elements List ...\n");
for (p = 0; p < 10; p++){
printf("%d\n", *(g+p));
}
return 0;
}
Output :
Printing Sorted Elements List ....
7
9
10
12
23
23
34
44
78
101
Comments
Post a Comment