The Wayback Machine - https://web.archive.org/web/20240717024803/https://www.geeksforgeeks.org/how-arrays-are-passed-to-functions-in-cc/
Open In App

Pass Array to Functions in C

Last Updated : 04 Dec, 2023
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

In C, the whole array cannot be passed as an argument to a function. However, you can pass a pointer to an array without an index by specifying the array’s name.

Arrays in C are always passed to the function as pointers pointing to the first element of the array.

Syntax

In C, we have three ways to pass an array as a parameter to the function. In the function definition, use the following syntax:

return_type foo ( array_type array_name[size], ...);

Mentioning the size of the array is optional. So the syntax can be written as:

return_type foo ( array_type array_name[], ...);

In both of the above syntax, even though we are defining the argument as array it will still be passed as a pointer. So we can also write the syntax as:

return_type foo ( array_type* array_name, ...);

But passing an array to function results in array decay due to which the array loses information about its size. It means that the size of the array or the number of elements of the array cannot be determined anymore.

passing array to function in c

 

Examples of Passing Array to Function in C

Example 1: Checking Size After Passing Array as Parameter

C




// C program to pass the array as a function and check its size
#include <stdio.h>
#include <stdlib.h>
 
// Note that arr[] for fun is just a pointer even if square
// brackets are used. It is same as
// void fun(int *arr) or void fun(int arr[size])
void func(int arr[8])
{
    printf("Size of arr[] in func(): %d bytes",
           sizeof(arr));
}
 
// Drive code
int main()
{
    int arr[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };
 
    printf("Size of arr[] in main(): %dbytes\n",
           sizeof(arr));
 
    func(arr);
 
    return 0;
}


Output

Size of arr[] in main(): 32bytes
Size of arr[] in func(): 8 bytes

As we can see,

  • The size of the arr[] in the main() function (where arr[] is declared) is 32 bytes which is = sizeof(int) * 8 = 4 * 8 = 32 bytes.
  • But in the function where the arr[] is passed as a parameter, the size of arr[] is shown as 8 bytes (which is the size of a pointer in C).

It is due to the fact that the array decays into a pointer after being passed as a parameter. One way to deal with this problem is to pass the size of the array as another parameter to the function. This is demonstrated in the below example.

Example 2: Printing Array from the Function

C




// C program to illustrate the use of sizeof operator in C
#include <stdio.h>
 
// function to print array
void printArray(int arr[], int size)
{
    printf("Array Elements: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
}
 
// driver code
int main()
{
    int arr[8] = { 12, 4, 5, 3, 7, 8, 11, 45 };
 
    // getting the size of array
    int size = sizeof(arr) / sizeof(arr[0]);
 
    printArray(arr, size);
 
    return 0;
}


Output

Array Elements: 12 4 5 3 7 8 11 45 

This size parameter may not be needed only in the case of ‘\0’ terminated character arrays as size can be determined by checking the end of the string character. The below example demonstrates the following.

Example 3: Printing Array of Characters (String) using Function

C




// C Program to print the string using a function
#include <stdio.h>
 
// function to print the string
void printString(char* str)
{
    printf("Array of Characters: ");
 
    int i = 0;
    while (str[i] != '\0') {
        printf("%c ", str[i]);
        i++;
    }
}
 
// Driver program
int main()
{
    char arr[] = "String";
 
    printString(arr);
 
    return 0;
}


Output

Array of Characters: S t r i n g 

As we can see, we were able to deduce the end of the string (character array) using a NULL Character. Moreover, the %s specifier in printf() function uses the same principle so we can directly use this to print string.

Predict the Output of the Below C Programs

Program 1:

C




#include <stdio.h>
 
void fun(int arr[], unsigned int n)
{
    int i;
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
}
 
// Driver program
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
    unsigned int n = sizeof(arr) / sizeof(arr[0]);
    fun(arr, n);
    return 0;
}


Program 2:

C




#include <stdio.h>
void fun(int* arr)
{
    int i;
    unsigned int n = sizeof(arr) / sizeof(arr[0]);
    for (i = 0; i < n; i++)
        printf("%d  ", arr[i]);
}
 
// Driver program
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
    fun(arr);
    return 0;
}


Hint: For the 64-bit processor, the size of the pointer is 8 bytes and the size of the integer is 4 bytes.

Program 3:

C




#include <stdio.h>
#include <string.h>
 
void fun(char* arr)
{
    int i;
    unsigned int n = strlen(arr);
    printf("n = %d\n", n);
    for (i = 0; i < n; i++)
        printf("%c  ", arr[i]);
}
 
// Driver program
int main()
{
    char arr[] = "geeksquiz";
    fun(arr);
    return 0;
}


Program 4:

C




#include <stdio.h>
#include <string.h>
 
void fun(char* arr)
{
    int i;
    unsigned int n = strlen(arr);
    printf("n = %d\n", n);
    for (i = 0; i < n; i++)
        printf("%c  ", arr[i]);
}
 
// Driver program
int main()
{
    char arr[]
        = { 'g', 'e', 'e', 'k', 's', 'q', 'u', 'i', 'z' };
    fun(arr);
    return 0;
}


NOTE: The character array in the above program is not ‘\0’ terminated. (See this for details)

Frequently Asked Questions (FAQs)

Q1. Why can’t we use NULL to terminate the integer or float array?

Answer:

In C, the null by default is equivalent to 0. So if we want to use NULL as an ending point for an integer or float array, we won’t be able to use 0 as a value of the array element. In some specific cases, it may work but in general, it is meaningless to sacrifice one of the most commonly used digit for this purpose.

Q2. Why does C not allow passing an array by value to the function?

Answer:

The array names in C are inherently treated as a pointer to the first element of the array in most contexts including passing as a parameter. So, when we use the array name to pass it as a parameter, the value of the array name is actually copied to the formal parameter of the function (as happens in call by value), but the value that is copied is the address of the first element. So it seems like the arrays are passed as reference.

Related Articles:



Previous Article
Next Article

Similar Reads

Pass Array to Functions in C++
In C++, a collection of elements stored in contiguous memory locations and having the same data type is called an array. Passing arrays to functions is done to perform various operations on array elements without messing up with the main code. In C++, an array can be passed in a function using a pointer or reference. Understanding the different app
5 min read
C++ Functions - Pass By Reference
Several ways exist in which data (or variables) could be sent as an argument to a function. Two of the common ones are Passing by Value and Passing by Reference. Passing by reference allows a function to modify a variable without creating a copy. We have to declare reference variables. The memory location of the passed variable and parameter is the
5 min read
How to pass a 2D array as a parameter in C?
This post is an extension of How to dynamically allocate a 2D array in C? A one dimensional array can be easily passed as a pointer, but syntax for passing a 2D array to a function can be difficult to remember. One important thing for passing multidimensional arrays is, first array dimension does not have to be specified. The second (and any subseq
3 min read
How to pass an array by value in C ?
In C, array name represents address and when we pass an array, we actually pass address and the parameter receiving function always accepts them as pointers (even if we use [], refer this for details). How to pass array by value, i.e., how to make sure that we have a new copy of array when we pass it to function? This can be done by wrapping the ar
2 min read
Pass the value from child process to parent process
Prerequisite: Pipe() and Fork() Basic Write a C program in which the child process takes an input array and send it to the parent process using pipe() and fork() and then print it in the parent process. Examples: Suppose we have an array a[]={1, 2, 3, 4, 5} in child process, then output should be 1 2 3 4 5. Input: 1 2 3 4 5 Output: 1 2 3 4 5 // C p
2 min read
Determine the number of squares of unit area that a given line will pass through.
Given 2 endpoints (x1, y1) and (x2, y2) of a line, the task is to determine the number of squares of the unit area that line will pass through. Examples: Input: (x1 = 1, y1 = 1), (x2 = 4, y2 = 3) Output: 4 In the diagram above the line is passing through 4 squaresInput: (x1 = 0, y1 = 0), (x2 = 2, y2 = 2) Output: 2 Approach: Let, Dx = (x2 - x1) Dy =
4 min read
How to Pass or Return a Structure To or From a Function in C?
A structure is a user-defined data type in C. A structure collects several variables in one place. In a structure, each variable is called a member. The types of data contained in a structure can differ from those in an array (e.g., integer, float, character). Syntax: struct geeksforgeeks { char name[20]; int roll_no; char branch[20]; } How to Pass
3 min read
Pass By Reference In C
Passing by reference is a technique for passing parameters to a function. It is also known as call by reference, call by pointers, and pass by pointers. In this article, we will discuss this technique and how to implement it in our C program. Pass By Reference in C In this method, the address of an argument is passed to the function instead of the
4 min read
When do we pass arguments by pointer?
In C, the pass-by pointer method allows users to pass the address of an argument to the function instead of the actual value. This allows programmers to change the actual data from the function and also improve the performance of the program. In C, variables are passed by pointer in the following cases: 1. To Modify Local Variables of the Function
5 min read
When Do We Pass Arguments by Reference or Pointer in C++?
In C++, we can pass arguments to a function as a value, reference (or pointer). Each method has its unique benefits and uses. In this article, we will discuss the application or cases where we should pass the arguments by reference or a pointer. But first, let’s quickly revisit the definitions of pointers and references. Pointers in C++ Pointers ar
4 min read
three90RightbarBannerImg