Suppose we want to create a class for Graph. The class stores adjacency matrix representation of the graph. Therefore, our class structure would be something like below.
error: invalid use of non-static data member 'Graph::V'.
Even if we make V static, we get error “array bound is not an integer constant”
C++ doesn’t allow to create an 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 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
A note on call of memset():
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 like below 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 you want to share more information about the topic discussed above
- Lexicographically next permutation in C++
- How to print size of array parameter in C++?
- How to split a string in C/C++, Python and Java?
- How to dynamically allocate a 2D array in C?
- C++ string class and its applications
- Functions in C/C++
- Inline Functions in C++
- How to find size of array in C/C++ without using sizeof ?
- Arrays in C/C++
- C++ String Class and its Applications | Set 2
- Counts of distinct consecutive sub-string of length two using C++ STL
- Binary Search functions in C++ STL (binary_search, lower_bound and upper_bound)
- Multidimensional Arrays in C / C++
- Default Arguments in C++
- new and delete operators in C++ for dynamic memory