The Wayback Machine - https://web.archive.org/web/20240828111558/https://www.geeksforgeeks.org/multidimensional-arrays-in-c/
Open In App

Multidimensional Arrays in C

Last Updated : 11 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite: Arrays in C

A multi-dimensional array can be termed as an array of arrays that stores homogeneous data in tabular form. Data in multidimensional arrays is generally stored in row-major order in the memory.

The general form of declaring N-dimensional arrays is shown below.

Syntax:

data_type array_name[size1][size2]....[sizeN];
  • data_type: Type of data to be stored in the array.
  • array_name: Name of the array.
  • size1, size2,…, sizeN: Size of each dimension.

Examples:

Two dimensional array: int two_d[10][20];

Three dimensional array: int three_d[10][20][30];

Size of Multidimensional Arrays:

The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions.
For example:

  • The array int x[10][20] can store total (10*20) = 200 elements.
  • Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.

To get the size of the array in bytes, we multiply the size of a single element with the total number of elements in the array.
For example:

  • Size of array int x[10][20] = 10 * 20 * 4  = 800 bytes.      (where int = 4 bytes)
  • Similarly, size of int x[5][10][20] = 5 * 10 * 20 * 4 = 4000 bytes.      (where int = 4 bytes)

The most commonly used forms of the multidimensional array are:

  1. Two Dimensional Array
  2. Three Dimensional Array

Two-Dimensional Array in C

A two-dimensional array or 2D array in C is the simplest form of the multidimensional array. We can visualize a two-dimensional array as an array of one-dimensional arrays arranged one over another forming a table with ‘x’ rows and ‘y’ columns where the row number ranges from 0 to (x-1) and the column number ranges from 0 to (y-1).

graphical representation of two dimensional array

Graphical Representation of Two-Dimensional Array of Size 3 x 3

Declaration of Two-Dimensional Array in C

The basic form of declaring a 2D array with x rows and y columns in C is shown below.

Syntax:

data_type array_name[x][y];

where,

  • data_type: Type of data to be stored in each element.
  • array_name: name of the array
  • x: Number of rows.
  • y: Number of columns.

We can declare a two-dimensional integer array say ‘x’ with 10 rows and 20 columns as:

Example:

int x[10][20];

Note: In this type of declaration, the array is allocated memory in the stack and the size of the array should be known at the compile time i.e. size of the array is fixed. We can also create an array dynamically in C by using methods mentioned here.

Initialization of Two-Dimensional Arrays in C

The various ways in which a 2D array can be initialized are as follows:

  1. Using Initializer List
  2. Using Loops

1. Initialization of 2D array using Initializer List

We can initialize a 2D array in C by using an initializer list as shown in the example below.

First Method:

int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}

The above array has 3 rows and 4 columns. The elements in the braces from left to right are stored in the table also from left to right. The elements will be filled in the array in order: the first 4 elements from the left will be filled in the first row, the next 4 elements in the second row, and so on.

Second Method (better):

int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};

This type of initialization makes use of nested braces. Each set of inner braces represents one row. In the above example, there is a total of three rows so there are three sets of inner braces. The advantage of this method is that it is easier to understand.

Note: The number of elements in initializer list should always be less than or equal to the total number of elements in the array.

We can also declare the array without defining the size of the row if we are using list initialization. The compiler will automatically deduce the size of the array in this case:

data_type array_name[][y] = {...} ;

It is still compulsory to define the number of columns.

2. Initialization of 2D array using Loops

We can use any C loop to initialize each member of a 2D array one by one as shown in the below example.

Example:

int x[3][4];

for(int i = 0; i < 3; i++){
    for(int j = 0; j < 4; j++){
        x[i][j] = i + j;
    }
}

This method is useful when the values of each element have some sequential relation.

Accessing Elements of Two-Dimensional Arrays in C

Elements in 2D arrays are accessed using row indexes and column indexes. Each element in a 2D array can be referred to by:

Syntax:

array_name[i][j]

where,

  • i: The row index.
  • j: The column index.

Example: 

int x[2][1];

The above example represents the element present in the third row and second column.

Note: In arrays, if the size of an array is N. Its index will be from 0 to N-1. Therefore, for row index 2 row number is 2+1 = 3. To output all the elements of a Two-Dimensional array we can use nested for loops. We will require two ‘for‘ loops. One to traverse the rows and another to traverse columns.

For printing the whole array, we access each element one by one using loops. The order of traversal can be row-major order or column-major order depending upon the requirement. The below example demonstrates the row-major traversal of a 2D array.

Example:

C




// C Program to print the elements of a
// Two-Dimensional array
 
#include <stdio.h>
 
int main(void)
{
    // an array with 3 rows and 2 columns.
    int x[3][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
 
    // output each array element's value
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 2; j++) {
            printf("Element at x[%i][%i]: ", i, j);
            printf("%d\n", x[i][j]);
        }
    }
 
    return (0);
}
 
// This code is contributed by sarajadhav12052009


Output

Element at x[0][0]: 0
Element at x[0][1]: 1
Element at x[1][0]: 2
Element at x[1][1]: 3
Element at x[2][0]: 4
Element at x[2][1]: 5

Time Complexity: O(N*M) , where N(here 3) and M(here 2) are numbers of rows and columns respectively.

Space Complexity:O(1)

How 2D Arrays are Stored in the Memory?

The elements of the 2-D array have to be stored contiguously in memory. As the computers have linear memory addresses, the 2-D arrays must be linearized so as to enable their storage. There are two ways to achieve linearization of array elements:

  • Row-major- The linearization technique stores firstly the first row of the array, then the second row of the array, then the third row, and so on. (i.e. elements are stored row-wise. Rows are listed on the basis of columns)
  • Column-major– This linearization technique stores first the first column, then the second column, then the third column, and so on i.e. (elements are stored column-wise. Columns are listed on the basis of rows)

The computer does not keep track of the addresses of all the elements of the array but does keep track of the Base Address (starting address of the very first element) and calculates the addresses of the elements when required.

To know more, refer to the article – Calculation of address of element of 1-D, 2-D, and 3-D

Three-Dimensional Array in C

A Three Dimensional Array or 3D array in C is a collection of two-dimensional arrays. It can be visualized as multiple 2D arrays stacked on top of each other.

graphical representation of three dimensional array

Graphical Representation of Three-Dimensional Array of Size 3 x 3 x 3

Declaration of Three-Dimensional Array in C

We can declare a 3D array with x 2D arrays each having y rows and z columns using the syntax shown below.

Syntax:

data_type array_name[x][y][z];
  • data_type: Type of data to be stored in each element.
  • array_name: name of the array
  • x: Number of 2D arrays.
  • y: Number of rows in each 2D array.
  • z: Number of columns in each 2D array.

Example:

int array[3][3][3];

Initialization of Three-Dimensional Array in C

Initialization in a 3D array is the same as that of 2D arrays. The difference is as the number of dimensions increases so the number of nested braces will also increase.

A 3D array in C can be initialized by using:

  1. Initializer List
  2. Loops

Initialization of 3D Array using Initializer List

Method 1:

int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 
                 11, 12, 13, 14, 15, 16, 17, 18, 19,
                 20, 21, 22, 23};

Method 2(Better):  

int x[2][3][4] = 
{
{ {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },
{ {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }
};

Again, just like the 2D arrays, we can also declare the 3D arrays without specifying the size of the first dimensions if we are using initializer list for initialization. The compiler will automatically deduce the size of the first dimension. But we still need to specify the rest of the dimensions.

data_type array_name[][y][z] = {....};

Initialization of 3D Array using Loops

It is also similar to that of 2D array with one more nested loop for accessing one more dimension.

int x[2][3][4];

for (int i=0; i<2; i++) {
    for (int j=0; j<3; j++) {
        for (int k=0; k<4; k++) {
            x[i][j][k] = (some_value);
        }
    }
}

Accessing elements in Three-Dimensional Array in C

Accessing elements in 3D Arrays is also similar to that of 2D Arrays. The difference is we have to use three loops instead of two loops for one additional dimension in 3D Arrays.

Syntax:

array_name[x][y][z]

where,

  • x: Index of 2D array.
  • y: Index of that 2D array row.
  • z: Index of that 2D array column.

C




// C program to print elements of Three-Dimensional Array
 
#include <stdio.h>
 
int main(void)
{
    // initializing the 3-dimensional array
    int x[2][3][2] = { { { 0, 1 }, { 2, 3 }, { 4, 5 } },
                       { { 6, 7 }, { 8, 9 }, { 10, 11 } } };
 
    // output each element's value
    for (int i = 0; i < 2; ++i) {
        for (int j = 0; j < 3; ++j) {
            for (int k = 0; k < 2; ++k) {
                printf("Element at x[%i][%i][%i] = %d\n", i,
                       j, k, x[i][j][k]);
            }
        }
    }
    return (0);
}


Output

Element at x[0][0][0] = 0
Element at x[0][0][1] = 1
Element at x[0][1][0] = 2
Element at x[0][1][1] = 3
Element at x[0][2][0] = 4
Element at x[0][2][1] = 5
Element at x[1][0][0] = 6
Element at x[1][0][1] = 7
Element at x[1][1][0] = 8
Element at x[1][1][1] = 9
Element at x[1][2][0] = 10
Element at x[1][2][1] = 11

In similar ways, we can create arrays with any number of dimensions. However, the complexity also increases as the number of dimensions increases. The most used multidimensional array is the Two-Dimensional Array.

Arrays are also closely related to pointers in C language. To know more about the Relationship of Arrays with Pointers in C, refer to this article.



Previous Article
Next Article

Similar Reads

Initialization of Multidimensional Arrays in C++
In C++, multidimensional arrays are the type of arrays that have multiple dimensions, i.e., they can expand in multiple directions. In this article, we will discuss how to initialize the multidimensional arrays in C++. Methods to Initialize Multidimensional Array in C++We can initialize multidimensional arrays in C++ using the following ways: Initi
3 min read
How to print dimensions of multidimensional array in C++
Create a function that prints multidimensional array size by dimensions i.e.:Examples: Input : int a[2][3][4]; printDimensions(a); Output : 2x3x4 Input : int b[5][6]; printDimensions(a); Output : 5x6 To solve this problem we should use template function to figure out the size of current array. Then we call this function recursively till the last di
2 min read
C++ Multidimensional Array
An array is a type of data structure used to store the collection of the same data type items held at contiguous memory locations. Arrays can be one-dimensional or multidimensional based on the number of directions in which the array can grow. In this article, we will study multidimensional arrays such as two-dimensional arrays and three-dimensiona
9 min read
Multidimensional Pointer Arithmetic in C/C++
In C/C++, arrays and pointers have similar semantics, except on type information. As an example, given a 3D array int buffer[5][7][6]; An element at location [2][1][2] can be accessed as "buffer[2][1][2]" or *( *( *(buffer + 2) + 1) + 2). Observe the following declaration T *p; // p is a pointer to an object of type T When a pointer p is pointing t
4 min read
Associative arrays in C++
Associative arrays are also called map or dictionaries. In C++. These are special kind of arrays, where indexing can be numeric or any other data type i.e can be numeric 0, 1, 2, 3.. OR character a, b, c, d... OR string geek, computers... These indexes are referred as keys and data stored at that position is called value. So in associative array we
2 min read
How to find common elements between two Arrays using STL in C++?
Given two arrays, find common elements between these two arrays using STL in C++. Example: Input: arr1[] = {1, 45, 54, 71, 76, 12}, arr2[] = {1, 7, 5, 4, 6, 12} Output: {1, 12} Input: arr1[] = {1, 7, 5, 4, 6, 12}, arr2[] = {10, 12, 11} Output: {1, 4, 12} Approach: Common elements can be found with the help of set_intersection() function provided in
2 min read
Count of distinct sums that can be obtained by adding prime numbers from given arrays
Given two arrays arr1[] and arr2[]. The task is to count the distinct sums that can be obtained while choosing a prime element from arr1[] and another prime element from arr2[].Examples: Input: arr1[] = {2, 3}, arr2[] = {2, 2, 4, 7} Output: 4 All possible prime pairs are (2, 2), (2, 2), (2, 7), (3, 2), (3, 2) and (3, 7) with sums 4, 4, 9, 5, 5 and
6 min read
Arrays and Strings in C++
Arrays An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They are used to store similar types of elements as in the data type must be the same for all elements. They can be used to store the collection of primitive data types such as int, float, doubl
5 min read
Jagged Arrays in C++
Prerequisite: Arrays in C++ An array of pointers in C++Dynamic 2D arrays in C++What is a Jagged Array? A jagged array is an array of arrays such that member arrays can be of different sizes, in 2D array terms for each row we can have a variable number of columns. These types of arrays are also known as Jagged arrays. Example: arr[3][] = 1 2 3 4 //
4 min read
Difference between Arrays and Pointers
The array and pointers are derived data types that have lots of differences and similarities. In some cases, we can even use pointers in place of an array, and arrays automatically get converted to pointers when passed to a function. So, it is necessary to know about the differences between arrays and pointers to properly utilize them in our progra
7 min read
Quickly merging two sorted arrays using std::merge() in C++ STL
C++ program to merge two sorted arrays of length 'n' and 'm' respectively in sorted order. Examples: Input: A[] = {3, 6, 9} B[] = {2, 7, 11} Output: C[] = {2, 3, 6, 7, 9, 11} Input: A[] = {1, 1, 3, 6, 9} B[] = {1, 2, 7, 11, 11} Output: C[] = {1, 1, 1, 2, 3, 6, 7, 9, 11, 11} We have discussed other approaches in below posts Merge two sorted arrays w
2 min read
Why is a[i] == i[a] in C/C++ arrays?
The definition of [] subscript operator operator in C, according to (C99, 6.5.2.1p2), is that E1[E2] is identical to (*((E1)+(E2))) Compilers use pointer arithmetic internally to access array elements. And because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of
2 min read
One Dimensional Arrays in C++
One-dimensional arrays are like a row of boxes where you can store things where each box can hold one item, such as a number or a word. For example, in an array of numbers, the first box might hold 5, the second 10, and so on. You can easily find or change what's in each box by referring to its position, called an index. Arrays are handy because th
6 min read
C++ Arrays
In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location. For example, if we have to store the marks of 4 or 5 students then we can easily store them by creating 5 different variables but what if we want to store marks of 100 students or say 500 students then it becomes very ch
14 min read
Variable Length Arrays (VLAs) in C
In C, variable length arrays (VLAs) are also known as runtime-sized or variable-sized arrays. The size of such arrays is defined at run-time. Variably modified types include variable-length arrays and pointers to variable-length arrays. Variably changed types must be declared at either block scope or function prototype scope. Variable length arrays
2 min read
Is std::vector So Much Slower Than Plain Arrays?
In C++, std::vector is a dynamic array provided by the Standard Template Library (STL), and it is commonly compared to plain arrays. A frequent question that arises is: Is std::vector significantly slower than plain arrays? The straightforward answer is no, std::vector is not significantly slower, though there are some performance differences we ne
6 min read
How to quickly swap two arrays of same size in C++?
Given two arrays a[] and b[] of same size, we need to swap their contents. Example : Input: a[] = {1, 2, 3, 4} b[] = {5, 6, 7, 8}Output: a[] = {5, 6, 7, 8}b[] = {1, 2, 3, 4} A simple solution is to iterate over elements of both arrays and swap them one by one. A quick solution is to use std::swap(). It can directly swap arrays if they are of same s
2 min read
Complete Guide to Arrays Data Structure
In this complete guide to Array Data Structures, you will learn about the basics of Arrays, how to get started with Array, learning, strategy, resources, problems, and much more.
4 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
30 OOPs Interview Questions and Answers (2024)
Object-Oriented Programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is &lt;string&gt;. The substring function takes two values pos and len as an argument
8 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which holds its own data members and member functions, w
9 min read
Priority Queue in C++ Standard Template Library (STL)
A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority {fixed order}). In C++ STL, the top elemen
11 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
10 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the &lt;map&gt; header file. Basic std::map Member FunctionsSome basic functions associated with std::
8 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
9 min read
Templates in C++ with Examples
A template is a simple yet very powerful tool in C++. The simple idea is to pass the data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types. Rather than writing and maintaining multiple codes, we can write one sort() and pass the dat
10 min read
Friend Class and Function in C++
A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node. We can declare a friend class in C++ by using the
6 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
Article Tags :
Practice Tags :