1

I have a pretty specific data structure issue that I cannot figure out. For my assignment, I must have a dynamically allocated array of structures in my private section of my header. So, up to this point, in my header file, I have

struct node{
  int name;
  node *next;};  

In my private, I have

node *adj;

which is, at least to my knowledge, how you would set up having the array.
Then, in my .cpp file, I have

adj = new node*[];

This is throwing a bunch of errors. But, when I have

node *adj[n];

in my cpp and nothing in my header, it works. My questions is how do I have an array in my private section of my header, but dynamically allocate the space in my .cpp?

3
  • node *adj; is not an array of pointers, it is a pointer to node. node **adg would be an array of pointers. Commented May 2, 2013 at 5:45
  • @EdS. The title says array of pointers, the text says array of structures. Having thought about it I guess an array of pointers is what is really required. Commented May 2, 2013 at 5:46
  • @john: Yeah, I was going off of this: adj = new node*[]; Commented May 2, 2013 at 5:48

1 Answer 1

2

You have defined

node *adj;

which is a pointer to a node, or an array of nodes. If you want an array of pointers to nodes, you should declare

node **adj;

which is a pointer to a pointer to a node, or an array of pointers to nodes. In the first case, you allocate the array using

adj = new node[n];

which defines an array of nodes. and in the second you use

adj = new node*[n];

which defines an array of node pointers.

adj = new node*[];

should not make sense as it does not tell the compiler how big to make the array.

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

1 Comment

This is exactly what I needed. The second version worked perfectly.

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.