0

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

1 Answer 1

1

Operator new initializes memory to zero

Since you are not initializing the array once it is created, it could have any value.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.