How to Create a Dynamic 2D Array Inside a Class in C++?
A dynamic array is an array that can grow, resize itself, contains a dynamic table, which is mutable in nature, or an array list is randomly accessible, the variable-size list data structure that allows elements to be added or removed.
Suppose we want to create a class for Graph. The class stores the adjacency matrix representation of the graph.
error: invalid use of non-static data member 'Graph::V'.
Even if we make V static, we get the error “array bound is not an integer constant”.
C++ doesn’t allow to creation of a stack-allocated array in a class whose size is not constant. So we need to dynamically allocate memory. Below is a simple program to show how to dynamically allocate a 2D array in a C++ class using a class for Graph with adjacency matrix representation.
0 1 1 0 0 0 1 0 1 0 0 1 0 0 0 1
Note: memset() is used separately for individual rows. We can’t replace these calls with one call because rows are allocated at different addresses and making a memset call would be disastrous.
// Wrong!! (Rows of matrix at different addresses) memset(adj, false, V*V*sizeof(bool));
This article is contributed by Dheeraj Gupta. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.