Creating an array of pointers.

Hello again,
I'm working on concept of RPG text game.
I decided, that class Location should have many members, and I'm not sure if I'm going right way.

For example, let's think about NPCs. NPC is a 'living' creature, that sometimes can leave one location and go to another.
Thinking that way, I came to conclusion, that NPC should be declared elsewhere, and Location should only have a pointer to that NPC.
But on one location there can be many NPCs. That's why I need an array of pointers.
Also, I don't know how many NPCs are on one location, and this amount can vary. That's why I guess I should use word NEW to declare them.

I've played a bit with arrays and new, and I have no idea how should I declare it and make it work.
My idea was to create something like this:
 
NPC* npcs = new NPC* [x];//I get amount of NPCs somewhere else 

But that won't work, since this declaration is somewhat wrong.
Is it possible to make it work, or is my whole concept wrong? Or maybe it's possible, but I should use vector/list to declare it?
I'm asking because I've never used vector nor list, so I'm not familiar with them.

Thanks in advance.
closed account (zb0S216C)
MatthewRock wrote:
"I don't know how many NPCs are on one location, and this amount can vary. That's why I guess I should use word NEW to declare them."

No. Use a std::vector. If you insist on using new, then I recommend implementing a simple linked-list[1], since they allow addition and removal of nodes, and expansion of its node count.

References:
[1] http://www.codeproject.com/Articles/24684/How-to-create-Linked-list-using-C-C


Wazzak
Actually, using vector would be a better idea - you won't need to store the number of NPC's separately and you won't have to care about memory management as well.

As for your code, it is in fact incorrect. You should write:
NPC* npcs = new NPC[x]; // notice no star on the right side

If you use NPC* on the right side - you allocate the array of pointers to NPC's (not an array of NPC's), and you probably get an error saying "cannot convert from NPC** to NPC*".

If you really want to stick to manual dynamically allocated arrays - don't forget to free the memory at some point using a correct delete operator:
delete [] npcs;
Last edited on
Thank you all for your help. I guess I will give vector a try. :)
Topic archived. No new replies allowed.