The Wayback Machine - https://web.archive.org/web/20240927020746/https://www.geeksforgeeks.org/initialize-multidimensional-array-in-c/
Open In App

Initialization of Multidimensional Array in C

Last Updated : 09 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C, initialization of a multidimensional array can have left most dimensions as optional. Except for the leftmost dimension, all other dimensions must be specified.

For example, the following program fails in compilation because two dimensions are not specified.

C




#include <stdio.h>
int main()
{
    int a[][][2] = { { { 1, 2 }, { 3, 4 } },
                     { { 5, 6 }, { 7, 8 } } }; // error
    printf("%d", sizeof(a));
    getchar();
    return 0;
}


Output

./Solution.cpp: In function 'int main()':
./Solution.cpp:5:14: error: declaration of 'a' as multidimensional array must have bounds for all dimensions except the first
int a[][][2] = { {{1, 2}, {3, 4}},
^
./Solution.cpp:7:18: error: 'a' was not declared in this scope
cout << sizeof(a);
^

Multidimensional Array can be initialized using an initializer list as shown:

Syntax

array_name[x][y] = { {a, b, c, ... }, ........., { m, n, o ...}};

Following 2 programs work without any error.

C




// Program 1
#include <stdio.h>
int main()
{
    int a[][2] = { { 1, 2 }, { 3, 4 } }; // Works
    printf("%lu", sizeof(a)); // prints 4*sizeof(int)
    getchar();
    return 0;
}


Output

16

C




// Program 2
#include <stdio.h>
int main()
{
    int a[][2][2] = { { { 1, 2 }, { 3, 4 } },
                      { { 5, 6 }, { 7, 8 } } }; // Works
    printf("%lu", sizeof(a)); // prints 8*sizeof(int)
    getchar();
    return 0;
}


Output

32

The below example is multidimensional array in  C.

C




#include <stdio.h>
  
int main()
{
  
    // code
    int a[2][3] = { { 1, 3, 2 }, { 6, 7, 8 } };
    int i, j;
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 3; j++) {
            printf("\n a[%d][%d]=%d", i, j, a[i][j]);
        }
    }
    return 0;
}


Output

 a[0][0]=1
 a[0][1]=3
 a[0][2]=2
 a[1][0]=6
 a[1][1]=7
 a[1][2]=8

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



Previous Article
Next Article

Similar Reads

How to Get Value of Multidimensional Array in C?
Prerequisite: Array in C An array is a type of data structure where we can store multiple elements of similar data types. A multidimensional array can be termed an array of arrays that stores homogeneous data in tabular form. Data in multidimensional arrays are stored in row-major order. Declaration of Array Declaration or Initialisation of an arra
8 min read
How does C allocate memory of data items in a multidimensional array?
The data items in a multidimensional array are stored in the form of rows and columns. Also, the memory allocated for the multidimensional array is contiguous. So the elements in multidimensional arrays can be stored in linear storage using two methods i.e., row-major order or column-major order. Row major order: In row-major order, we store the el
4 min read
Implicit initialization of variables with 0 or 1 in C
In C programming language, the variables should be declared before a value is assigned to it. For Example: // declaration of variable a and // initializing it with 0. int a = 0; // declaring array arr and initializing // all the values of arr as 0. int arr[5] = {0}; However, variables can be assigned with 0 or 1 without even declaring them. Let us
2 min read
Initialization of data members
In C++, class variables are initialized in the same order as they appear in the class declaration. Consider the below code. #include<iostream> using namespace std; class Test { private: int y; int x; public: Test() : x(10), y(x + 10) {} void print(); }; void Test::print() { cout<<"x = "<<x<<" y = "<
1 min read
Initialization of variables sized arrays in C
The C99 standard allows variable sized arrays (see this). But, unlike the normal arrays, variable sized arrays cannot be initialized. For example, the following program compiles and runs fine on a C99 compatible compiler. #include<stdio.h> int main() { int M = 2; int arr[M][M]; int i, j; for (i = 0; i < M; i++) { for (j = 0; j < M; j++)
1 min read
Initialization of global and static variables in C
Predict the output of following C programs. // PROGRAM 1 #include <stdio.h> #include <stdlib.h> int main(void) { static int *p = (int*)malloc(sizeof(p)); *p = 10; printf("%d", *p); } // PROGRAM 2 #include <stdio.h> #include <stdlib.h> int *p = (int*)malloc(sizeof(p)); int main(void) { *p = 10; printf("%d"
1 min read
Initialization of static variables in C
In C, static variables can only be initialized using constant literals. For example, following program fails in compilation. [GFGTABS] C #include<stdio.h> int initializer(void) { return 50; } int main() { static int i = initializer(); printf(" value of i = %d", i); getchar(); return 0; } [/GFGTABS]If we change the program to followi
1 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
Multidimensional Arrays in C - 2D and 3D Arrays
Prerequisite: Arrays in C A multi-dimensional array can be defined as an array that has more than one dimension. Having more than one dimension means that it can grow in multiple directions. Some popular multidimensional arrays are 2D arrays and 3D arrays. In this article, we will learn about multidimensional arrays in C programming language. Synta
10 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
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
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
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
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
Sort an array using socket programming in C
Given an array of unsorted positive integer, sort the given array using the Socket programming . Examples: Input : 4 5 6 1 8 2 7 9 3 0 Output :0 1 2 3 4 5 6 7 8 9 Input : 9 8 1 4 0 Output : 0 1 4 8 9 Compile these files using gcc command (gcc client.c -o client and gcc server.c -o server). Run the program using ./server and ./client (Please note :
3 min read
4 Dimensional Array in C/C++
Prerequisite :Array in C/C++, More on array A four-dimensional (4D) array is an array of array of arrays of arrays or in other words 4D array is a array of 3D array. More dimensions in an array means more data be held, but also means greater difficulty in managing and understanding arrays. Declaration of a Multidimensional Array in C: Syntax: data_
3 min read
Input an integer array without spaces in C
How to input a large number (a number that cannot be stored even in long long int) without spaces? We need this large number in an integer array such that every array element stores a single digit. Input : 10000000000000000000000000000000000000000000000 We need to read it in an arr[] = {1, 0, 0...., 0} In C scanf(), we can specify count of digits t
2 min read
Different ways to Initialize all members of an array to the same value in C
An array is a collection of data that holds fixed number of values of same type. For example: if you want to store marks of 100 students, you can create an array for it. int num[100]; How to declare an array in C? Data_type array_name[size_of_array]; For example, float num[10]; Below are some of the different ways in which all elements of an array
3 min read
Difference between Structure and Array in C
Array in C An array is collection of items stored at contiguous memory locations. Structure in C A structure is a user defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. Difference between Structure and Array ARRAYSTRUCTUREArray refers to a collection consistin
2 min read
C program to Insert an element in an Array
Given an array arr of size n, this article tells how to insert an element x in this array arr at a specific position pos. An array is a collection of items stored at contiguous memory locations. In this article, we will see how to insert an element in an array in C. Follow the below steps to solve the problem: First get the element to be inserted,
2 min read
Count ways to reach the Nth stair using any step from the given array
Given N stairs and a person standing at the bottom wants to reach the top. He could climb any number of steps from the given array arr[] of positive integers. The task is to find the count of all possible ways to reach the top. Examples: Input: arr[] = {1, 3, 5}, N = 5 Output: 5 (0 -> 1 -> 2 -> 3 -> 4 -> 5), (0 -> 1 -> 2 ->
10 min read
Duplicates Removal in Array using BST
Given an array arr[] of integers, the task is to remove duplicates from the given array. Examples: Input: arr[] = {1, 2, 3, 2, 5, 4, 4} Output: arr[] = {1, 2, 3, 4, 5} Input: arr[] = {127, 234, 127, 654, 355, 789, 355, 355, 999, 654} Output: arr[] = {127, 234, 355, 654, 789, 999} The duplicates in the array can be removed using Binary Search Tree.
7 min read
Move all zeroes to end of array using Two-Pointers
Given an array of random numbers, Push all the zero’s of the given array to the end of the array. For example, if the given arrays is {1, 0, 2, 6, 0, 4}, it should be changed to {1, 2, 6, 4, 0, 0}. The order of all other elements should be the same.Examples: Input: arr[]={8, 9, 0, 1, 2, 0, 3} Output: arr[]={8, 9, 1, 2, 3, 0, 0} Explanation: Swap {0
6 min read
Reverse an array in groups of given size | Set 3 (Single traversal)
Given an array, reverse every sub-array formed by consecutive k elements. Examples: Input: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3. Output: [3, 2, 1, 6, 5, 4, 9, 8, 7, 10]Input: arr = [1, 2, 3, 4, 5, 6, 7], k = 5. Output: [5, 4, 3, 2, 1, 7, 6] Approach: We will use two pointers technique to solve this problem.First, we will initialize our 1st
6 min read
Difference between Array and Union in C
1. Array in C : An array is collection of similar data items accessed by a common name stored at continuous memory locations. The elements of an array can be accessed using indices. They can be used to store primitive data types such as int, float, double, char, etc. but all elements have to be of the same data type. Below is the picturesque repres
2 min read
How to Declare and Initialize an Array of Pointers to a Structure in C?
Prerequisite: Structure in CArray in C In C language, arrays are made to store similar types of data in contiguous memory locations. We can make arrays of either primitive data types, like int, char, or float, or user-defined data types like Structures and Unions. We can also make arrays of pointers in C language. Today we will learn how to create
8 min read
How to declare a Two Dimensional Array of pointers in C?
A Two Dimensional array of pointers is an array that has variables of pointer type. This means that the variables stored in the 2D array are such that each variable points to a particular address of some other element. How to create a 2D array of pointers: A 2D array of pointers can be created following the way shown below. int *arr[5][5]; //creati
3 min read
Article Tags :