C How to Make an Array Then Feed the Whole Array to a Function

Learn how to pass an array to a function in C.

Abstract

An array is an effective way to group and store similar data together. We are required to pass an array to function several times, like in merge or quicksort. An array can be passed to functions in C using pointers by passing reference to the base address of the array, and similarly, a multidimensional array can also be passed to functions in C. Array can be returned from functions using pointers by sending the base address of an array or by creating user-defined data type, and this pointer can be used to access elements stored in the array.

Scope of article

  • This article discusses about passing an array to functions in C. Linear arrays and multi-dimension arrays can be passed and accessed in a function, and we will also understand how an array is stored inside memory and how the address of an individual element is calculated.
  • We also learn different ways to return an array from functions.
  • Advantages and disadvantages of passing an array to function are also discussed in the article.
  • This article does not discuss how arrays are initialized in different programming languages.

Introduction

An array is a collection of similar data types which are stored in memory as a contiguous memory block. This means multi-dimensional arrays are also a continuous block of data in our memory. In C, there are several times when we are required to pass an array to a function argument. For example, we have a function to sort a list of numbers; it is more efficient to pass these numbers as an array to function than passing them as variables since the number of elements the user has is not fixed and passing numbers as an array will allow our function to work for any number of values.

In this article, we will understand how we can pass an array to a function in C and return an array from functions in C using several different approaches.

Contiguous Memory Locations

Every C function can have arguments passed to it in either of two ways:

  1. Pass by value
  2. Pass by reference

Since arrays are a continuous block of values, we can pass the reference of the first memory block of our array to the function, and then we can easily calculate the address of any element in the array using the formula -

            
                                  address(arr[i]) = (start address of                                    array                  ) + i * (size of individual element)                                                

This way, we can easily pass an array to function in C by its reference.

Example: How Arrays are Passed in C?

In the example mentioned below, we have passed an array arr to a function that returns the maximum element present inside the array.

            
                                  #                  include                  <stdio.h>                                                                        int                                                      maxArray                  (                  int                  [],                                    int                  )                  ;                                                      int                                                      main                  ()                                                      {                                                                        int                                      arr[] = {                  4                  ,                                    3                  ,                                    1                  ,                                    6                  ,                                    5                  };                                                                        // passing array to the function                                                                                          int                                      max_element = maxArray(arr,                                    5                  );                                                                        printf                  (                  "Max element in array = %d"                  , max_element);                                                                        return                                                      0                  ;                  }                                                       int                                                      maxArray                  (                  int                                                      array                  [],                                    int                                      n)                                                      {                                                                        int                                      max_element =                                    array                  [                  0                  ], i;                                                                        for                                      (i =                                    1                  ; i < n; i++) {                                                                        if                                      (                  array                  [i] > max_element) {                                                        max_element =                                    array                  [i];                                    }                     }                                                      return                                      max_element;                  }                              

Output:

        

Methods to Pass an Array as an Argument

Arrays can be passed to function using either of two ways.

  1. Passing array as a pointer variable
                
  2. Passing array as reference
                

Compiler breaks either approach to a pointer to the base address of the array, i.e. int* array so passing int array[3] or int array[] or int* array breaks down to the same thing and to access any element of array compiler can find its value stored in location calculated using the formula stated above. This we are passing the array to function in C as pass by reference.

C Function to Sort the Array

            
                                  #                  include                  <stdio.h>                                                                        void                                                      BubbleSort                  (                  int                                                      array                  [],                                    int                                      n)                                                      {                                                                        int                                      i, j;                                                                        for                                      (i =                                    0                  ; i < n -                                    1                  ; i++) {                                                                        for                                      (j = i +                                    1                  ; j < n; j++) {                                                                        if                                      (                  array                  [j] <                                    array                  [i]) {                                                                        int                                      temp =                                    array                  [i];                                                                        array                  [i] =                                    array                  [j];                                                                        array                  [j] = temp;                                    }                       }                                        }                                                                         // no need to return array because,                                                                                          // array is passed by reference                                    }                                                       void                                                      main                  ()                                                      {                                                                        int                                      arr[                  6                  ] = {                  1                  ,                                    4                  ,                                    6                  ,                                    2                  ,                                    6                  ,                                    5                  };                                                                        // passing array to the function                                                                          BubbleSort(arr,                                    6                  );                                                                        printf                  (                  "Sorted array = "                  );                                                                        int                                      i =                                    0                  ;                                                                        for                                      (i =                                    0                  ; i <                                    6                  ; i++) {                                                                        printf                  (                  "%d, "                  , arr[i]);                                    }                   }                              

Output:

            
                                  Sorted                                    array                                      =                                    1                  ,                                    2                  ,                                    4                  ,                                    5                  ,                                    6                  ,                                    6                  ,                                                

In this example, we pass an array to a function in C, and then we perform our sort inside the function. Because we have passed the array by reference, changes on the array persist when the program leaves the scope of the function.

Returning an Array from a Function

We can return an array from a function in C using four ways

  1. Returning the array passed to function
  2. Returning dynamically created array
  3. Return array using static array
  4. Returning array using struct

For the first three cases, we can return the array by returning a pointer pointing to the base address of the array.

1. Returning the array passed in the function

            
                                  int                  *                                    foo                  (                  int                                                      array                  [])                                                      {                                                                        // do something                                                                                          return                                                      array                  ;                  }                              

2. Returning Dynamically Created Array

Dynamically create an array inside the function and then return a pointer to the base address of this array.

            
                                  #                  include                  <malloc.h>                                                                        int                  *                                    foo                  (                  int                                      n)                                                      {                                                                        // creating an array of n numbers                                                                                          int                                      *                  array                                      = (                  int                  *)                  malloc                  (n *                                    sizeof                  (                  int                  ));;                                                                        // do something with the array                                                                                          return                                                      array                  ;                  }                              

3. Return Array Using Static Array

We can create a static array that will make the array available throughout the program. Therefore, we can return the actual memory address of this static array.

            
                                  int                  *                                    foo                  ()                                                      {                                                                        static                                                      int                                                      array                  [                  5                  ];                                                                        // do something with the array                                                                                          return                                                      array                  ;                  }                              

4. Returning Array Using Struct

We can create our own data type using the keyword struct in C, which has an array inside it, and this data type can be returned from the function.

            
                                  #                  include                  <stdio.h>                                                                        #                  include                  <malloc.h>                                                                        struct                                                      OurArray                                      {                                                                                          // user-defined data type containing an array                                                                                          int                                                      array                  [                  5                  ];                  };                                                       struct OurArray                                    getArray                  ()                                                      {                                                                        struct                                                      OurArray                                                      arr                  ;                                                                                          int                                      i;                                                                        printf                  (                  "Enter 5 elements \n"                  );                                                                        for                                      (i =                                    0                  ; i <                                    5                  ; i++) {                                                                        scanf                  (                  "%d"                  , & arr.                  array                  [i]);                                    }                                                      // return our struct                                                                                          return                                      arr;                  }                                                       void                                                      main                  ()                                                      {                                                                        struct                                                      OurArray                                                      arr                                      =                                      getArray();                                                                        int                                      i;                                                                        printf                  (                  "Five elements of array are = "                  );                                                                        for                                      (i =                                    0                  ; i <                                    5                  ; i++) {                                                                        printf                  (                  "%d, "                  , arr.                  array                  [i]);                                    }                   }                              

Pass Individual Array Elements

To pass individual elements of an array to a function, the array name along with its subscripts inside square brackets [] must be passed to function call, which can be received in simple variables used in the function definition.

1. Example: Pass Individual Array Elements

            
                                  #                  include                  <stdio.h>                                                                        void                                                      printElement                  (                  int                                      element,                                    int                                      index)                                                      {                                                                        // here, array elements are passed by value                                                                                          printf                  (                  "Element at index %d = %d \n"                  , index, element);                  }                                                       void                                                      main                  ()                                                      {                                                                        int                                      arr[                  5                  ] = {                  2                  ,                                    4                  ,                                    5                  }, i;                                                                        for                                      (i =                                    0                  ; i <                                    3                  ; i++) {                                    printElement(arr[i], i);                     }                   }                              

2. Example: Pass Array to Functions

            
                                  #                  include                  <stdio.h>                                                                        void                                                      printArrayElements                  (                  int                                      * arr,                                    int                                      n)                                                      {                                                                        // here, array elements are passed by value                                                                                          int                                      i;                                                                        for                                      (i =                                    0                  ; i < n; i++) {                                                                        printf                  (                  "Element at index %d = %d \n"                  , i, arr[i]);                                    }                   }                                                       void                                                      main                  ()                                                      {                                                                        int                                      arr[                  3                  ] = {                  2                  ,                                    4                  ,                                    5                  };                                                        printArrayElements(arr,                                    3                  );                  }                              

Output of both functions are same,

            
                                  Element at index                                    0                                      =                                    2                                                      Element at index                                    1                                      =                                    4                                                      Element at index                                    2                                      =                                    5                                                                  

Pass Multidimensional Array to a Function

Let us understand how we can pass a multidimensional array to functions in C.

Pass Multidimensional Array to Functions in C

Passing 2-D array to functions

To pass a 2-D array in a function in C, there is one thing we need to take care of that is we should pass the column size of the array along with the array name. So, we can pass the 2-D array in either of two ways.

            
                                  void                                                      foo                  (                  int                                                      array                  [                  3                  ][                  4                  ])                                                                                    

or

          

Example: Pass Two-dimensional Arrays

            
                                  #                  include                  <stdio.h>                                                                        void                                                      printArray                  (                  int                                                      array                  [                  3                  ][                  3                  ])                  ;                                                      void                                                      main                  ()                                                      {                                                                        int                                      arr[                  3                  ][                  3                  ] = {{                  1                  ,                                    2                  ,                                    3                  },{                  4                  ,                                    5                  ,                                    6                  },{                  7                  ,                                    8                  ,                                    9                  }};                                    printArray(arr);                   }                                                       void                                                      printArray                  (                  int                                                      array                  [                  3                  ][                  3                  ])                                                      {                                                                        int                                      i, j;                                                                        for                  (i =                                    0                  ; i <                                    3                  ; i++) {                                                                        for                  (j =                                    0                  ; j <                                    3                  ; j++) {                                                                        printf                  (                  "%d "                  ,                                    array                  [i][j]);                                    }                                                      printf                  (                  "\n"                  );                                    }                   }                                                 

Output:

          

Why is it compulsory to pass column size in arguments?

To answer this, we need to understand how 2-D arrays are arranged in memory. Just like a linear array, 2-D arrays are also stored in a contiguous arrangement that is one row after another, as shown in the figure.

Pass Column Size in Arguments

So our previous formula to calculate the N^th^ element of an array will not work here. The new formula will be if an array is defined as arr[n][m] where n is the number of rows and m is the number of columns in the array, then,

            
                                  address(arr[i][j]) = (                  array                                      base address) + (i * m + j) * (element size)                                                

As we can see from the above example, for the compiler to know the address of arr[i][j] element, it is important to have the column size of the array (m). This is the reason why passing int array[][] to the function will result in a compiler error.

So passing something like

          

will break down to int** array syntactically, it will not be an error, but when you try to access array[1][3] compiler will not be able to tell which element you want to access, but if we pass it as an array to function as

          

compiler will break this to something like int (*array)[4] and compiler can find the address of any element like array[1][3] which will be &array[0][0] + (1*4 + 4)*(sizeof(int)) because compiler knows second dimension (column size).

Example: Row Wise Sorting of a 2-D Array

            
                                  #                  include                  <stdio.h>                                                                        void                                                      BubbleSort                  (                  int                                                      array                  [],                                    int                                      n)                                                      {                                                                        int                                      i, j;                                                                        for                                      (i =                                    0                  ; i < n -                                    1                  ; i++) {                                                                        for                                      (j = i +                                    1                  ; j < n; j++) {                                                                        if                                      (                  array                  [j] <                                    array                  [i]) {                                                                        int                                      temp =                                    array                  [i];                                                                        array                  [i] =                                    array                  [j];                                                                        array                  [j] = temp;                                    }                       }                     }                   }                                                       void                                                      BubbleSort2DArray                  (                  int                                                      array                  [][                  3                  ],                                    int                                      n)                                                      {                                                                        int                                      i =                                    0                  ;                                                                        for                                      (i =                                    0                  ; i < n; i++) {                                                                        // passing address of 1st element of ith row                                                                          BubbleSort(                  array                  [i],                                    3                  );                                    }                   }                                                       void                                                      printArray                  (                  int                                                      array                  [                  3                  ][                  3                  ])                                                      {                                                                        int                                      i, j;                                                                        for                                      (i =                                    0                  ; i <                                    3                  ; i++) {                                                                        for                                      (j =                                    0                  ; j <                                    3                  ; j++) {                                                                        printf                  (                  "%d"                  ,                                    array                  [i][j]);                                    }                                                      printf                  (                  "\n"                  );                                    }                   }                                                       void                                                      main                  ()                                                      {                                                                        int                                      arr[                  3                  ][                  3                  ] = {{                  1                  ,                                    4                  ,                                    5                  }, {                  4                  ,                                    2                  ,                                    1                  }, {                  9                  ,                                    8                  ,                                    3                  }};                                                        BubbleSort2DArray(arr,                                    6                  );                                    printArray(arr);                   }                              

Output

          

Pass 2-D array as a single pointer

We can also pass a 2-D array as a single pointer to function, but in that case, we need to calculate the address of individual elements to access their values.

            
                                  #                  include                  <stdio.h>                                                                        void                                                      printArray                  (                  int                  * arr,                                    int                                      n,                                    int                                      m)                                                      {                                                                        for                  (                  int                                      i =                                    0                  ; i < n; i++) {                                                                        for                  (                  int                                      j =                                    0                  ; j < m; j++) {                                                                        int                                      element = *((arr + i * m) + j);                                                                        printf                  (                  "%d "                  , element);                                    }                                                      printf                  (                  "\n"                  );                                    }                   }                                                       void                                                      main                  ()                                                      {                                                                        int                                      arr[                  3                  ][                  3                  ] = {{                  1                  ,                                    4                  ,                                    5                  }, {                  4                  ,                                    2                  ,                                    1                  }, {                  9                  ,                                    8                  ,                                    3                  }};                                                        printArray(arr,                                    3                  ,                                    3                  );                  }                                                 

Output:

          

Similarly, to pass an array with more than one dimension to functions in C, we can either pass all dimensions of the array or omit the first parameter and pass the remaining element to function, for example, to pass a 3-D array function will be

            
                                  void                                                      foo                  (                  int                                                      array                  [][                  3                  ][                  4                  ])                                                      {                                                                        // do something                                    }                              

or

            
                                  void                                                      foo                  (                  int                                                      array                  [                  3                  ][                  3                  ][                  4                  ])                                                      {                                                                        // do something                                    }                              

Example Demonstrating Passing Array as Reference

When we pass an array to functions by reference, the changes which are made on the array persist after we leave the scope of function. This can be demonstrated from this example-

            
                                  #                  include                  <stdio.h>                                                                        void                                                      incrementArray                  (                  int                                      arr[],                                    int                                      n)                                                      {                                                                        int                                      i;                                                                        for                                      (i =                                    0                  ; i < n; i++) {                                                        arr[i] +=                                    1                  ;                                    }                   }                                                       void                                                      main                  ()                                                      {                                                                        int                                      arr[] = {                  1                  ,                                    2                  ,                                    3                  ,                                    4                  ,                                    5                  ,                                    6                  }, i;                                                        incrementArray(arr,                                    6                  );                                                                        for                                      (i =                                    0                  ; i <                                    6                  ; i++) {                                                                        printf                  (                  "%d "                  , arr[i]);                                    }                   }                              

Output:

        

Receiving array as a pointer variable

As we have discussed above array can be returned as a pointer pointing to the base address of the array, and this pointer can be used to access all elements in the array. The below example demonstrates the same.

            
                                  #                  include                  <stdio.h>                                                                        #                  include                                                      <stdlib.h>                                                                        int                  *                                    generateArray                  (                  int                                      n)                                                      {                                                                        // dynamically creating an array of required size                                                                                          int                  *                                    array                                      = (                  int                  *)                  malloc                  (n *                                    sizeof                  (                  int                  ));                                                                        int                                      i;                                                                        for                                      (i =                                    0                  ; i < n; i++) {                                                                        array                  [i] = rand() %                                    100                  ;                                    // random number between 0 - 100                                                                        }                                                      return                                                      array                  ;                  }                                                       void                                                      main                  ()                                                      {                                                                        int                                      i =                                    0                  , n =                                    10                  ;                                                                        int                  * arr = generateArray(n);                                                                        for                                      (i =                                    0                  ; i < n; i++) {                                                                        printf                  (                  "%d "                  , *(arr + i));                                                                        // or printf("%d", arr[i]);                                                      }                   }                              

Output:

            
                                  83                                                      86                                                      77                                                      15                                                      93                                                      35                                                      86                                                      92                                                      49                                                      21                                                                  

Advantages of Passing Arrays to Functions

  1. Passing similar elements as an array takes less time than passing each element to a function as we are only passing the base address of the array to the function, and other elements can be accessed easily as an array is a contiguous memory block of the same data types.
  2. As we pass reference of base address of the array, this means the compiler doesn't create a copy of the array to process inside function which is faster and less memory-intensive compared to passing arguments by value.
  3. Because arrays are passed by reference to functions, this prevents stack memory overflow in the case of recursive functions.

Disadvantages of Passing Arrays to Functions

  1. We can get garbage values if the user tries to access values beyond the size of the array, which can result in wrong outputs. To prevent this, the bound check should be used before accessing the elements of an array, and also, array size should be passed as an argument in the function.
  2. If the memory space is more than elements in the array, this leads to a wastage of memory space.
  3. Special care is required when dealing with a multidimensional array as all the dimensions are required to be passed in function.

Summary

  • Array can be passed to function in C using pointers, and because they are passed by reference, changes made on an array will also be reflected on the original array outside the function scope.
  • Arrays can be returned from functions in C using a pointer pointing to the base address of the array or by creating a user-defined data type using struct.
  • To pass a multidimensional array to function, it is important to pass all dimensions of the array except the first dimension.
  • Because arrays are passed by reference, it is faster as a new copy of the array is not created every time function is executed.

rodriguezsmor1940.blogspot.com

Source: https://www.scaler.com/topics/c/pass-array-to-function-in-c/

0 Response to "C How to Make an Array Then Feed the Whole Array to a Function"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel