views:

246

answers:

3

Hi,

I have

class Node
{
public:

string el1;
string el2;
string curr;
string name;
int ID1;
int ID2;

Node(){
//constructor is here
ID1=-1;
ID2=-1;
}

};

And it has 10 different nodes represented with array..

Node [] allNode=new Node[10];

for(i=0; i< 10; i++)
{
//create new node
allNode[i] = new Node();

std::string el = "f";
std::string el2 = "g";
std::string allNode[i].curr;

allNode[i].curr = name + boost::lexical_cast<std::string>(i);
cout << "Node name " << allNode[i].curr <<endl;

}

However, I have compile error as below:-

error: expected unqualified-id before ‘[’ token referring to Node [] allNode=new Node[10];
error: ‘allNode’ was not declared in this scope
error: ‘name’ was not declared in this scope

Please advise. Thanks.

+1  A: 

There are multiple problems in the code. First new Node[10] returns the address of the first object, so your statement should be Node* allNode = new Node[10]; . And I am not sure what is the meaning of this statement: std::string allNode[i].curr

Naveen
+1  A: 

In C++, you put the square brackets after the variable name, e.g.

Node allNode[10];

However, when dealing with dynamically-allocated arrays, use a pointer type:

Node *allNode = new Node[10];
Martin v. Löwis
A: 

The error comes from this line:
Node [] allNode=new Node[10]; Which should be:
Node* allNode=new Node[10];

You're also not accessing the members of Node correctly. See below for sample code:

int main
{
  Node* allNodes = new Node[10]; 

  for(i=0; i< 10; i++) 
  { 
    //create new node 
    allNodes[i] = new Node(); 

    allNodes[i]->el = "f"; 
    allNodes[i]->el2 = "g"; 
    allNodes[i]->curr = name + boost::lexical_cast<std::string>(i); 

    std::cout << "Node name " << allNodes[i]->curr << std::endl;    
  }

  delete [] allNodes;
}
Bill