×

Array to function in C

Array to function in C

We can create functions that receive an array as an argument. To pass an array into a function, we need to write the name of the array in the function call. We have to pass the size of an array as a parameter. Size may or may not be required.

Exclusion of size can be done in ‘\0’ terminated character arrays, and size can be determined by checking the end of the string character. You can pass both one dimensional and multi-dimensional arrays into the function.

A single array element or an entire array itself can be passed into the function. This passing of an array can be done for both one dimensional as well as a multi-dimensional array.

Syntax:

            function_name  (array_name);

Passing one dimensional array:

  • Passing individual array elements to a function is almost identical to passing variables to a function.

Eg:

 #include <stdio.h>
 void display (int height1, int height2)
 {
 printf (“ %d \n” , height1);
 printf (“ %d \n” , height2);
 }
 int main()
 {
 int heightArray[] = {162, 168, 164, 165};
 //passing index numbers to the get the output
 display (height1[2], height2[3]);
 return 0;
 } 

Output:

 164
 165 
  • Passing an entire array to a function using pointer

Eg:

 #include <stdio.h>
 float totalHeight (float height[]);
 int main()
 {
 float result, height[] = {162, 167, 164, 163};
 //array containing heights of students is passed to totalHeight()
 result = totalHeight(height);
 printf (“Result = %.2f”, result);
 return 0;
 }
 Float totalHeight (float height[])
 {
 float sum = 0.0;
 for (int i = 0; i < 4; ++i)
 {
 sum += height[i];
 }
 return sum;
 } 

Output:

            Result = 41

To pass an array to a function, the name of the specific array will be passed as an argument, such as, in the above example, we pass result = totalHeight(height);

Function definition has [], in it. It informs the compiler that you are passing one dimensional array to a function.

In the above code, we can see the code snippet:

 float totalHeight (float height[])
 {
 …
 } 
  • Passing an array using a pointer
 void printArray (int *arr, int size)
 {
 int i;
 printf (“Array elements are:”);
 for (i = 0; i < size; i++)
 {
 printf (“%d” , arr[i]);
 }
 }
 int main()
 {
 int arr[10];
 printArray(arr, 10) //passes array directly to function printArray
 return 0;
 } 

Passing multi-dimensional array:

The multi-dimensional array can be passed to a function in the same way as we pass a one dimensional array. There are two ways in which we can pass an array into a function.

  • Passing an array directly to a function:

The simplest way to pass a multi-dimensional array is to pass it as we would for any other variables.

E.g.:

 #include <stdio.h>
 #define row 3
 #define column 3
 void printArray (int arr[] [column]); // function declaration to print 2D array
 int main()
 {
 int arr [row][column] = {
 {2, 4, 8},
 {1, 3, 5},
 {6, 7, 9}
 };
 printArray (arr);
 return 0;
 }
 void printArray (int arr [][column])
 {
 int i, j;
 printf (“Elements in a matrix is : \n”);
 for ( i = 0; i < row; i++)
 {
 for ( j = 0; j < column; j++)
 {
 printf (“%d”, arr[i][j]);
 }
 printf (“\n”);
 }
 } 
  • Passing an array to a function using pointer:

Eg:

 #include <stdio.h>
 #define row 3
 #define column 3
 void inputArray (int (*arr) [column]); //function declaration
 void printArray (int arr[] [column]);
             int main()
             {
             int arr [row][column];
 inputArray (arr); //input elements into the matrix using the function
 printArray (arr); //print elements of the matrix using the function
 return 0;
 }
 void inputArray (int (*arr) [column])
 {
 int i, j;
 printf (“ Enter two dimensional array elements: \n”); //input elements in 2D
 for (i = 0; i < row; i++)
 {
 for (j = 0; j <column; j++)
 {
 scanf (“%d”, (*(arr + i) +j));
 }
 }
 }
 void printArray(int (*arr) [column])
 {
 int i, j;
 printf (“Elements in an array: \n”);
 for (i = 0; i < row; i++)
 {
 for (j = 0; j < column; j++)
 {
 printf (“%d”, *(*(arr+i) +j));
 }
 printf (“\n”);
 }
 } 

There are three ways to pass an array to a function in the C programming language:

  • Using blank subscript notation []
return-type function (type array-name[])
  • Defining size in subscript notation []
return-type function (type array-name[size])
  • Using pointer
return-type function (type *arrayname)

Advantages:

  • The array is passed as a pointer; hence the memory of the array will not be copied. The function uses the memory of the same array passed to it and can change everything in the memory.
  • It can move the memory management to a caller, making a function more general.

Disadvantages:

  • In the C programming language, you can always pass an array to a function, however, you cannot return arrays from functions in the same way.
  • It may require an argument other than the declared to communicate the array size.
  • It misunderstands the argument in the documentation.

Passing an array to a function is like a simple and, any programmer familiar with the concept can quickly implement it. Although one must remember that an array passed to function uses the ‘pass by reference’ concept.


Related Topics

Free() Function in C

Free() function is a built-in function which is define in the stdlib.h header file. If we want to use this function in our program, we must include the stdlib.h header...

4 minutes read.

Pointer in C

Pointer is a variable that is used to contain the address of another variable. We can easily create a pointer in C language. Example: int *ptr Symbol Description & (ampersand sign) Address of an operator...

1 minute read.

Multiplication Table in C

Displaying table up to 10 #include <stdio.h> int main() {     int num, i = 1;     printf("     Enter any Number:");     scanf("%d", &num);     printf("Multiplication table of %d: ", num);  ...

1 minute read.

Continue in C

C language: C language is a procedure oriented programming language. We can say that it is a platform dependent language. C language is introduced by Dennis Ritchie in the year 1970. We...

2 minutes read.

Ceil and Floor in C

In arithmetic, a rational number is a number that can be expressed as the quotient p/q of two integers. Where q is zero. The set of rational numbers includes all...

6 minutes read.

Floyd’s triangle in C

Floyd’s triangle in C Floyd’s triangle is named after a person Robert Floyd. It is a right-angled triangle that is of natural numbers starting from 1 and consecutively selects the upcoming...

4 minutes read.

Calendar application in C

Introduction to the calendar application We all are familiar with the calendar. It plays a crucial role in our daily life. We run toward the calendar whenever we want to know...

6 minutes read.

Find a subarray with a given sum.

Find a subarray with a given sum. The simple solution is to recognize all subarrays one by one and to check each subarray's sum. The quick solution follows the following program. Algorithm: From...

4 minutes read.

Cbrt() function in C

Introduction: The Cbrt is a function used in C programming language. The cbrt() function is a math function. Using the cbrt function, we can do the cube root of a function. This...

4 minutes read.

What is 2s Complement in C?

The complement of 2s in C is generated from the 1s in C. As we know, the 1s complement of a binary number is generated by converting bit 1 to...

4 minutes read.

Actual and Formal Parameters

Any variable declared within the parenthesis is referred to as the parameters during the function declaration. Parameters tell the function about the argument datatype, their order, and the number of...

5 minutes read.

Bubble sort in C

Bubble sort in C Bubble sort is defined as the algorithm that is used for the sorting mechanism. It follows the technique of replacing the first index with the more minor...

4 minutes read.

How to lock top row in Excel

How to lock top row in excel While working with an Excel spreadsheet, the user utilizes the rows and columns to enter the details under various headings. Sometimes while scrolling the...

4 minutes read.

Queue implementation in C

In the C programming language, the queue is the abstract concept that is similar to stacks. However, it is the part of the data structures that work opposite to that...

4 minutes read.

Flow Chart of Do while loop in C

This is a flowchart that represents the process of executing the Do while loop in the C programming language Generally, as we know there are three main components of Do While...

3 minutes read.

Doubly Linked list in C

To know the Doubly Linked List in C, first we should know about how the Linked List works. Linked List The Linked list is the linear data structure. In the Linked...

5 minutes read.

Comma Operator in C

What is a comma operator? The comma operator in the C programming language has the least priority. The comma operator is essentially a binary operator that operates on the first operand...

4 minutes read.

File Handling in C

File Handling is used to open, read, write, search and close file.  C files I/O functions handles data on secondary storage device. File handling function: There are varioushandling functions in C. Function Operation fopen() It is...

4 minutes read.

While-Loop in C

Syntax of While Loop The syntax that has been used for the while loop in C programming language is: while (termination condition) {   // the body of the loop  } Working of While-Loop Initially, we...

3 minutes read.

Snake Game in C

Snake game in C is basic desktop console program which was created in 1970’s. It is an old classic game which was played by every child across the world. This...

4 minutes read.