views:

43

answers:

2
class Node{
      private:
              string name;
              Node** adjacent;
              int adjNum;
      public:
             Node();
             Node(string, int adj_num);
             Node(const Node &);
             bool addAdjacent(const Node &);
             Node** getAdjacents();
             string getName();
             ~Node();
      };

bool Node::addAdjacent(const Node &anode){
     Node** temp;   
     temp= new Node*[adjNum+1];
     for(int i=0;i<adjNum+1;i++)
         temp[i]=adjacent[i];
     temp[adjNum]=const_cast<Node *>(&anode);
     delete[] adjacent;
     adjacent=new Node*[adjNum+1];
     adjacent=temp;
     delete[] temp;
     adjNum++;
     return true;
}

int main()
{
    Node node1("A",0);
    Node node2("B",0);
    node1.getName();
    node1.addAdjacent(node2);
    system("PAUSE");
    return 0;
}

when the program comes to this part:

for(int i=0;i<adjNum+1;i++)
     temp[i]=adjacent[i];

it says Access violation reading location 0xcccccccc. The class must allocate the memory fore adjacent, but I think it didn't how can I solve this problem?

+3  A: 
 adjacent=new Node*[adjNum+1];
 adjacent=temp;
 delete[] temp;

This looks like a bug. You probably meant to write:

adjacent = temp;

and that's it.

Also, I think the problem lies with

for(int i=0;i<adjNum+1;i++)

You're copying adjNum+1 elements, even though (I assume) adjacent only contains adjNum elements. Remove the +1 from the for loop.

strager
it's true I edited that part but also there is a memory allocation problem too as I mentioned up in the question. when creating the node1 object, I think it must create the pointer adjacent and allocate memory for it, but it just doesn't. The same error continues.
dbtek
+1  A: 

Besides the issues strager mentioned, you might be missing initialization for adjacent, e.g. like this:

Node::Node(std::string name, unsigned adj_num) 
  : name(name)
  , adjacent((adj_num > 0) ? new Node*[adj_num] : 0)
  , adjNum(adj_num)
{}

Note the unsigned parameter, a negative adj_num is most likely meaningless in this context.

If you don't initialize adjacent, it contains some garbage value and dereferencing it or passing it to delete[] leads to undefined behaviour.

Georg Fritzsche