Hi I am trying to initialize a 2D array using a constructor. But there is always a memeber of the resultant array being 48 (always located at graph[0][9]), when the size input is 9 or 10. Other sizes, i.e. 12, 13, ... , 20, don't have this problem. Please tell me what's has gone wrong. Thanks very much!
Do I need to assign values to each member and this has something to do with memory?
#include <iostream>
class Graph {
public:
Graph(int s=10);
void print_graph() const;
private:
int **graph;
int size;
};
// function to create a 2D array
Graph::Graph(int s)
{
size = s;
graph = new int* [size];
for (int i = 0; i < size; i++)
graph[i] = new int [size];
}
void Graph::print_graph() const
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
std::cout << graph[i][j] << " ";
std::cout << std::endl;
}
}
int main()
{
Graph g(9);
g.print_graph();
}
output:
0 0 0 0 0 0 0 0 48
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0