Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
How to dynamically allocate a 2D array in C?
Next article icon

How to declare a 2D array dynamically in C++ using new operator

Last Updated : 14 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisite: Array Basics
In C/C++, multidimensional arrays in simple words as an array of arrays. Data in multidimensional arrays are stored in tabular form (in row major order). Below is the general form of declaring N-dimensional arrays:

Syntax of a Multidimensional Array:

data_type array_name[size1][size2]….[sizeN];

data_type: Type of data to be stored in the array. 
Here data_type is valid C/C++ data type
array_name: Name of the array
size1, size2, …, sizeN: Sizes of the dimensions

2D arrays are arrays of single-dimensional arrays.

Syntax of a 2D array:

data_type array_name[x][y];
data_type: Type of data to be stored. Valid C/C++ data type.

Below is the diagrammatic representation of 2D arrays:

For more details on multidimensional and 2D arrays, please refer to Multidimensional arrays in C++ article.

Problem: Given a 2D array, the task is to dynamically allocate memory for a 2D array using new in C++.

Solution: Following 2D array is declared with 3 rows and 4 columns with the following values:

1 2 3 4 5 6 7 8 9 10 11 12

Note: Here M is the number of rows and N is the number of columns.

Method 1: using a single pointer – In this method, a memory block of size M*N is allocated and then the memory blocks are accessed using pointer arithmetic. Below is the program for the same:

C++




// C++ program to dynamically allocate
// the memory for 2D array in C++
// using new operator
#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
    // Dimensions of the 2D array
    int m = 3, n = 4, c = 0;
 
    // Declare a memory block of
    // size m*n
    int* arr = new int[m * n];
 
    // Traverse the 2D array
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
 
            // Assign values to
            // the memory block
            *(arr + i * n + j) = ++c;
        }
    }
 
    // Traverse the 2D array
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
 
            // Print values of the
            // memory block
            cout << *(arr + i * n + j)
                 << " ";
        }
        cout << endl;
    }
   
      //Delete the array created
      delete[] arr;
 
    return 0;
}
 
 

 
 

Output: 
1 2 3 4  5 6 7 8  9 10 11 12

 

 

Method 2: using an array of pointer: Here an array of pointers is created and then to each memory block. Below is the diagram to illustrate the concept:

 

 

Below is the program for the same:

 

C++




// C++ program to dynamically allocate
// the memory for 2D array in C++
// using new operator
#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
    // Dimensions of the array
    int m = 3, n = 4, c = 0;
 
    // Declare memory block of size M
    int** a = new int*[m];
 
    for (int i = 0; i < m; i++) {
 
        // Declare a memory block
        // of size n
        a[i] = new int[n];
    }
 
    // Traverse the 2D array
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
 
            // Assign values to the
            // memory blocks created
            a[i][j] = ++c;
        }
    }
 
    // Traverse the 2D array
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
 
            // Print the values of
            // memory blocks created
            cout << a[i][j] << " ";
        }
        cout << endl;
    }
 
    // Delete the array created
    for (int i = 0; i < m; i++) // To delete the inner
                                // arrays
        delete[] a[i];
    delete[] a; // To delete the outer array
                // which contained the pointers
                // of all the inner arrays
 
    return 0;
}
 
 

 
 

Output: 
1 2 3 4  5 6 7 8  9 10 11 12

 

 



Next Article
How to dynamically allocate a 2D array in C?
author
shahbazalam75508
Improve
Article Tags :
  • Arrays
  • C++
  • DSA
  • Technical Scripter
  • C++-new and delete
  • cpp-pointer
  • Pointers
  • Technical Scripter 2020
Practice Tags :
  • CPP
  • Arrays
  • Pointers

Similar Reads

  • 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 follo
    3 min read
  • How to Declare 3-Dimensional Arrays in Wiring in C?
    Prerequisite: Array in C Arrays are used the make a list of the same data type elements and store it in contiguous memory locations. In simple words, arrays are the organization of elements of the same data types. There are many types for declaring the array i.e, 1-Dimensional arrays, 2-Dimensional
    2 min read
  • How to dynamically allocate a 2D array in C?
    Following are different ways to create a 2D array on the heap (or dynamically allocate a 2D array).In the following examples, we have considered 'r' as number of rows, 'c' as number of columns and we created a 2D array with r = 3, c = 4 and the following values 1 2 3 4 5 6 7 8 9 10 11 12 1) Using a
    5 min read
  • new and delete Operators in C++ For Dynamic Memory
    In C++, when a variable is declared, the compiler automatically reserves memory for it based on its data type. This memory is allocated in the program's stack memory at compilation of the program. Once allocated, it cannot be deleted or changed in size. However, C++ offers manual low-level memory ma
    6 min read
  • How to dynamically allocate a 3D array in C++
    Prerequisite: Array BasicsIn C/C++, multidimensional arrays in simple words as an array of arrays. Data in multidimensional arrays are stored in tabular form (in row major order). Below is the general form of declaring N-dimensional arrays: Syntax of a Multidimensional Array: data_type array_name[si
    4 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
    8 min read
  • Sorting a dynamic 2-dimensional array of Strings
    Prerequisite: How to dynamically allocate a 2D array in C? Double pointer: A pointer pointing to another pointer is known as a Double pointer. To represent the double pointer ' ** ' is used. Double pointer is also called as pointer to pointer. Example: Input: Geeks, Gfg, Placement, Sudo, Gate Output
    5 min read
  • How to pass a 2D array as a parameter in C?
    A 2D array is essentially an array of arrays, where each element of the main array holds another array. In this article, we will see how to pass a 2D array to a function. The simplest and most common method to pass 2D array to a function is by specifying the parameter as 2D array with row size and c
    3 min read
  • Different Ways To Declare And Initialize 2-D Array in Java
    An array with more than one dimension is known as a multi-dimensional array. The most commonly used multi-dimensional arrays are 2-D and 3-D arrays. We can say that any higher dimensional array is an array of arrays. A very common example of a 2D Array is Chess Board. A chessboard is a grid containi
    5 min read
  • Dynamic Arrays and its Operations in Solidity
    The Dynamic arrays are the arrays that are allocated memory at the runtime and the memory is allocated from the heap. Syntax: // declaration of dynamic array int[] private arr; How They Are Different From Fixed Size Arrays? The fixed-size array has a fixed memory size whereas, in dynamic arrays, the
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences