0

So, I have two classes: Node and Graph. In the private section of Graph class I declare this:

int size;
Node* n;

In the Graph constructor I'm trying to create a dynamic array:

size=1;

Node *n = new Node[size];

But I'm getting an error: "Access violation reading location 0xcccccd44". How can I fix it? I know that I must be doing something wrong with the array, but I have no idea what and how to fix it.

Class Graph:

class Graph {
    friend class Node;

    private:
        int size;
        Node* n;

    public:
        Graph();
        Graph(int, Vertex*);
        ~Graph();
        void Draw(RenderWindow &);
        void Update(RenderWindow &, GameObject &, bool);
};

And two constructors:

Graph::Graph() {
    size=1;

    Node *n = new Node[size];
}

Graph::Graph(int s, Vertex p[]) {
    size=s;
    Node *n = new Node[size];
    for (int i=0; i<size; i++) {
        n[i].setNumer(i);
        n[i].setX(p[i].getX());
        n[i].setY(p[i].getY());
    }
}
6
  • You need to post more code, but I would guess you are not following the rule of three. Commented Nov 26, 2013 at 15:03
  • Well, there's really not much more code to add here... I'll put the code in the first post. Commented Nov 26, 2013 at 15:04
  • 1
    Did you mean to initialise the member n, rather than declaring a local variable with the same name? And why aren't you using std::vector<Node> to avoid all the problems you get with manual pointer-juggling? Commented Nov 26, 2013 at 15:05
  • 2
    Shouldn't that be n = new Node[size];, you are hiding your member variable n. Commented Nov 26, 2013 at 15:06
  • 1
    Use std::vector anyway. Commented Nov 26, 2013 at 15:10

2 Answers 2

2

You are redeclaring n in your constructor. You got it right with size but not with n. Like this

Graph::Graph(int s, Vertex p[]) {
    size=s;
    n = new Node[size];
    for (int i=0; i<size; i++) {
        n[i].setNumer(i);
        n[i].setX(p[i].getX());
        n[i].setY(p[i].getY());
    }
}

In your version you are initializing a local variable called n, which is different to the n declared in your class.

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

Comments

0

As I mentioned in my comment before you posted the rest of your code, you are hiding your member variable n here:

Node *n = new Node[size];
^^^^^^^

this declares a new automatic variable n which will not exist after you leave your constructor and will also leak memory, just change it to this:

n = new Node[size];

As others already mentioned using std::vector would be easier.

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.