For a homework assignment, we were assigned to make spanning trees for each graph, separate them by region and later display their spanning trees in ascending order.
I have a function that does breadth-first search to define connected components in a graph and later feed the region to a function that does the spanning tree for each region. I want to display my final spanning tree 2d arrays based on the number of "roads" or non-zero elements it has. All 2d arrays are adjacency matrixes.
I declared an array of 2d arrays in my class declaration as
int** spantreelist[10];
My trees are 2d adjacency matrixes, declared
int** trees;
and dynamically allocated later.
I assign my spantrees in this way:
spantreelist[newcount] = tree; //newcount = number of non 0 elements, different for each tree
for (int i = 0; i < 10; i++)
for (int y = 0; y < cities; y++)
for (int r = 0; r < cities; r++)
{
spantreelist[i][y][r] = tree[y][r];
}
However, when I call my final spantreelist later on to print my 2d arrays, I get a segmentation fault.
for (i = 0; i < 10; i++)
for (j = 0; j < cities; j++)
for (k = 0; k < cities; k++)
cout << spantreelist[i][j][k] <--- seg fault here.
The weird part is, if I just write cout << spantree[2][3][4] // 2
I get the value I wanted.
Any tips on how to properly put 2d arrays into an array would be great.
There is no such thing as "2d array" in C++. There are just arrays. Some of them happen to contain other arrays. Others contain pointers that sometimes point into yet other arrays. Referring to these constructs as 2D anything is misleading and best avoided.
You have an array of 10 pointers called spantreelist
.
spantreelist[newcount] = tree;
This assigns to a single element of the spantreelist
array, indexed newcount
. All other elements are not initialized.
for (i = 0; i < 10; i++)
....
spantreelist[i][y][r] = tree[y][r];
for (i = 0; i < 10; i++)
....
cout << spantreelist[i][j][k]
These two fragments access all elements of the spantreelist
array, indexed from 0 to 9. All of them but one are uninitialized. Accessing an uninitialized array element is undefined.
The best way to deal with arrays in C++ is via its standard library class templates std::vector
and std::array
.