The Wayback Machine - https://web.archive.org/web/20240926200233/https://www.geeksforgeeks.org/pass-2d-array-parameter-c/
Open In App

How to pass a 2D array as a parameter in C?

Last Updated : 06 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 subsequent) dimensions must be given
1) When both dimensions are available globally (either as a macro or as a global constant). 
 

C




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


Output

1 2 3 4 5 6 7 8 9 

2) When only second dimension is available globally (either as a macro or as a global constant). 
 

C




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


Output

1 2 3 4 5 6 7 8 9 

The above method is fine if second dimension is fixed and is not user specified. The following methods handle cases when second dimension can also change.
3) If compiler is C99 compatible 
From C99, C language supports variable sized arrays to be passed simply by specifying the variable dimensions (See this for an example run) 
 

C




// The following program works only if your compiler is C99 compatible.
#include <stdio.h>
 
// n must be passed before the 2D array
void print(int m, int n, int arr[][n])
{
    int i, j;
    for (i = 0; i < m; i++)
      for (j = 0; j < n; j++)
        printf("%d ", arr[i][j]);
}
 
int main()
{
    int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int m = 3, n = 3;
    print(m, n, arr);
    return 0;
}


Output

1 2 3 4 5 6 7 8 9 

If compiler is not C99 compatible, then we can use one of the following methods to pass a variable sized 2D array.
4) Using a single pointer 
In this method, we must typecast the 2D array when passing to function. 
 

C




#include <stdio.h>
void print(int *arr, int m, int n)
{
    int i, j;
    for (i = 0; i < m; i++)
      for (j = 0; j < n; j++)
        printf("%d ", *((arr+i*n) + j));
}
 
int main()
{
    int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int m = 3, n = 3;
 
    // We can also use "print(&arr;[0][0], m, n);" and "print((int *)arr[0], m, n);"
    print((int *)arr, m, n);
    return 0;
}


Output

1 2 3 4 5 6 7 8 9 

5) Using the concept of pointer to an array

C




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


Output

1 2 3 4 5 6 7 8 9 

References: 
http://www.eskimo.com/~scs/cclass/int/sx9a.html
This article is contributed by Abhay Rathi.
 



Previous Article
Next Article

Similar Reads

How to print size of array parameter in C++?
How to compute the size of an array CPP? C/C++ Code // A C++ program to show that it is wrong to  // compute size of an array parameter in a function #include <iostream> using namespace std; void findSize(int arr[]) { cout << sizeof(arr) << endl; } int main() { int a[10]; cout << sizeof(a) << " "; findSize(a)
3 min read
Difference between Argument and Parameter in C/C++ with Examples
Argument An argument is referred to the values that are passed within a function when the function is called. These values are generally the source of the function that require the arguments during the process of execution. These values are assigned to the variables in the definition of the function that is called. The type of the values passed in
4 min read
Parameter Passing Techniques in C
In C, there are different ways in which parameter data can be passed into and out of methods and functions. Let us assume that a function B() is called from another function A(). In this case, A is called the "caller function" and B is called the "called function or callee function". Also, the arguments which A sends to B are called actual argument
5 min read
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
Pass Array to Functions in C
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 th
6 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
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 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
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
What’s difference between “array” and “&array” for “int array[5]” ?
If someone has defined an array such as “int array[5]”, what’s the meaning of “array” or “&array”? Are they both same or are they different? You might be tempted to think that they both would point to the very first element of the array i.e. they both will have same address. Let us find out! To check this, the very first thing that comes to min
4 min read
array::front() and array::back() in C++ STL
Array classes are generally more efficient, light-weight, and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::front() This function is used to reference the first element of the array container. This function can be used to fetch the first element of an array. Synt
3 min read
array::fill() and array::swap() in C++ STL
Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::fill() This function is used to set a common value for all the elements of the array container. Syntax : arrayname.fill(value) Parameters : The value to be
3 min read
array::begin() and array::end() in C++ STL
Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::begin() begin() function is used to return an iterator pointing to the first element of the array container. begin() function returns a bidirectional iterat
3 min read
array::cbegin() and array::cend() in C++ STL
array::cbegin() is a built-in function in C++ STL which returns a const_iterator pointing to the first element in the array. It cannot be used to modify the element in the array which is possible using array::begin(). Syntax: array_name.cbegin() Parameters: The function does not accept any parameters. Return Value: The function returns a const_iter
2 min read
array::rbegin() and array::rend() in C++ STL
array::rbegin() is a built-in function in C++ STL which returns a reverse iterator pointing to the last element in the container. Syntax:array_name.rbegin()Parameters: The function does not accept any parameter. Return value: The function returns a reverse iterator pointing to the last element in the container. Program to demonstrate the array::rbe
2 min read
Difference between pointer to an array and array of pointers
Pointer to an array: Pointer to an array is also known as array pointer. We are using the pointer to access the components of the array. int a[3] = {3, 4, 5 }; int *ptr = a; We have a pointer ptr that focuses to the 0th component of the array. We can likewise declare a pointer that can point to whole array rather than just a single component of the
4 min read
Jagged Array or Array of Arrays in C with Examples
Prerequisite: Arrays in C Jagged array is array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D array but with a variable number of columns in each row. These type of arrays are also known as Jagged arrays. Example: arr[][] = { {0, 1, 2}, {6, 4}, {1, 7, 6, 8, 9}, {5} }; Below are the methods to implement the j
3 min read
Array of Structures vs Array within a Structure in C
Both Array of Structures and Array within a Structure in C programming is a combination of arrays and structures but both are used to serve different purposes. Array within a Structure A structure is a data type in C that allows a group of related variables to be treated as a single unit instead of separate entities. A structure may contain element
5 min read
Array of Structures vs Array within a Structure in C++
In C++, an array of structure and an array within structure are used frequently used for data storage. Although they sound similar, they work pretty differently from each other. In this article, we will discuss the key differences between an array of structures and an array within structures and clarify the confusion. Array of Structures in C++An a
4 min read
Pointer to an Array | Array Pointer
Prerequisite: Pointers Introduction  Consider the following program:  [GFGTABS] C #include<stdio.h> int main() { int arr[5] = { 1, 2, 3, 4, 5 }; int *ptr = arr; printf("%p\n", ptr); return 0; } [/GFGTABS]In the above program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a pointer
9 min read
Pointer vs Array in C
Most of the time, pointer and array accesses can be treated as acting the same, the major exceptions being: 1. the sizeof operator sizeof(array) returns the amount of memory used by all elements in the array sizeof(pointer) only returns the amount of memory used by the pointer variable itself 2. the & operator array is an alias for &array[0
1 min read
How to Return a Local Array From a C++ Function?
Here, we will build a C++ program to return a local array from a function. And will come across the right way of returning an array from a function using 3 approaches i.e. Using Dynamically Allocated ArrayUsing Static Array Using Struct C/C++ Code // C++ Program to Return a Local // Array from a function While // violating some rules #include <i
3 min read
Properties of Array in C
An array in C is a fixed-size homogeneous collection of elements stored at a contiguous memory location. It is a derived data type in C that can store elements of different data types such as int, char, struct, etc. It is one of the most popular data types widely used by programmers to solve different problems not only in C but also in other langua
8 min read
Program to reverse an array using pointers
Prerequisite : Pointers in C/C++ Given an array, write a program to reverse it using pointers . In this program we make use of * operator . The * (asterisk) operator denotes the value of variable . The * operator at the time of declaration denotes that this is a pointer, otherwise it denotes the value of the memory location pointed by the pointer .
4 min read
Sum of array using pointer arithmetic
Given an array, write a program to find the sum of array using pointers arithmetic. In this program we make use of * operator . The * (asterisk) operator denotes the value of variable. The * operator at the time of declaration denotes that this is a pointer, otherwise it denotes the value of the memory location pointed by the pointer . sum() functi
2 min read
array::operator[ ] in C++ STL
Array classes are generally more efficient, light-weight, and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::operator[] This operator is used to reference the element present at position given inside the operator. It is similar to the at() function, the only diffe
2 min read
array::size() in C++ STL
Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::size() size() function is used to return the size of the list container or the number of elements in the list container. Syntax : arrayname.size() Parameter
1 min read
array::empty() in C++ STL
Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::empty() empty() function is used to check if the array container is empty or not. Syntax : arrayname.empty() Parameters : No parameters are passed. Returns
1 min read