×

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

How to measure time taken by a function in C?

Measuring the time taken by a function is quite a complex task, because numerous methods are frequently not transferable to other platforms, measuring the execution time of a C programs...

5 minutes read.

Fseek Function in C

The fseek function is a function in the C standard library that changes the position of the file pointer in a stream-oriented file. It is typically used to move the...

3 minutes read.

Why C is a middle level language

The C programming language is generally referred to as a high level language but we glance through the backend of C, i.e the working of C as a programming language...

4 minutes read.

Static in C

Static is a keyword that is used in the C programming language. It can be used both as variables and as functions. In other words, it can be declared both...

3 minutes read.

Multilevel Feedback Queue Scheduling (MLFQ) CPU Scheduling

In this article, you will learn how to initialise an array to 0 in C In C, an array is declared as: char ZEROARRAY[2022]; The global scope changes at runtime to all zeros....

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.

C printf and Scanf

Input-Output functions in C Programming In C Language, the printf() and scanf() are inbuilt library functions that used for input and output. It is defined in the header file“<stdio.h>”. printf() Function: In C...

2 minutes read.

Execution flow of C program

There are various steps of the execution of the C program that is given below. The following step of the execution Write source codes Preprocess Compile Link edit Load Execute Editor or...

1 minute read.

Ferror() in c

Ferror():  In C, the ferror() function checks assuming there is a blunder in the given stream. The ferror() function is utilized to check for the document blunder on given stream. A return...

4 minutes read.

For Loop in C

The Syntax of For Loop for (initialization statement; test expression; update statement) {     /* main body of the FOR loop */ } How does For loop work? In for loop, the initialization command is...

3 minutes read.

Add two numbers using the function in C

Here we will learn how to add two numbers by creating function in C. Let’s learn this with help of example. Code: - #include <stdio.h> int add_two_no(int a, int b); int main(){   int first_num,...

1 minute read.

Find occurrence of substring in C using function

Introduction: In this article, we discuss finding the occurrence of a substring in C using function. This software takes strings and substrings as input and counts the occurrences of substrings within...

3 minutes read.

Ceil function in C

Introduction In the C Programming Language, the ceil function is a library function which is used to obtain the ceil value, i.e., it returns the smallest integer that is greater than...

4 minutes read.

Types of Array in C

What is an Array? One value can be stored in a variable at once. How many variables will you need if you have 100 values? Well, the answer isn't 100. It...

14 minutes read.

C Language Environment Setup

To compile C program, we must have GCC compiler installed on our machine. In this C tutorial, all the examples are compiled and tested using GCC compiler. Although we can...

3 minutes read.

gets() function in C

gets() is a pre-define or built-in function present in the stdio.h header file. stdio stands for standard input and output. gets() function is used to read a stream and store...

4 minutes read.

Kruskal algorithm in C

Given a weighted graph, Kruskal's algorithm generates a spanning tree with the lowest possible weights. Start by creating an edge list for the given graph, including the weights. Sort the...

3 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.

Fahrenheit to Celsius in C

Before going into conversion, we have to know what Fahrenheit and Celsius mean, these are both units to measure the temperature.In our daily life, we use both Fahrenheit and Celsius,...

1 minute read.

What is a buffer in C?

A buffer is an area of memory set aside for the temporary storage of data. A data buffer (or just buffer) is a region of a physical memory storage used to...

5 minutes read.