Sign in to follow this  
grekster

Pointer to an Array of Pointers.

Recommended Posts

Thanks to everyone whos posted in my other threads so far, my text adventure is going well:) To the problem.... Basically I have an array of pointers like so cNPC* NPCList[3]; declared in a class. I want to pass a pointer to this array out of a function so I can copy out the values, so I created a function cNPC* ReturnNPCList(); Firstly is that the right to pass a pointer to an array of cNPC* the function contains one line. return(this->NPCList); then I had cNPC* NPCList = Map.ReturnNPCList() and this wouldnt compile. After some fiddling about in a seperate program I got a pointer defined as type** name to work but it doesnt work with my function. Ive been searching about on google and havent been able to find an answer so any help would be much appreciated!

Share this post


Link to post
Share on other sites
You're on the right track with type**. This:

cNPC** ReturnNPCList() {return NPCList;}

cNPC** list = ReturnNPCList();

Should work, unless there's some syntax or compiler issue I'm not aware of (admittedly, I don't think I've ever tried exactly what you're doing).

If that doesn't work, perhaps:

{return &NPCList[0];}

Will.

Anyway, here's an even better idea. Use a std::vector<cNPC*>, and pass it around as a reference.

Share this post


Link to post
Share on other sites
NPCList would decay to a pointer to cNPC*, so cNPC**. You could also return a pointer to cNPC*[3], though the syntax isnt that great.


//return by pointer to array of size 3 of pointers to cNPC
cNPC* (*ReturnNPCList())[3]{
return &NPCList;
}


//return by reference to array of size 3 of pointers to cNPC
cNPC* (&ReturnNPCList())[3]{
return NPCList;
}



That could obviously benefit from some typedefs.


typedef cNPC* (*pointertoarray)[3];
typedef cNPC* (&referencetoarray)[3];

//return by pointer to array of size 3 of pointers to cNPC
pointertoarray ReturnNPCList(){
return &NPCList;
}


//return by reference to array of size 3 of pointers to cNPC
referencetoarray ReturnNPCList(){
return NPCList;
}


Hope that helps.

Share this post


Link to post
Share on other sites
Changing the function decleration to cNPC** fixed it! Pretty obivous really if im trying to out it into a variable thats cNPC**
I'm kicking myself for not spotting it lol.

Thanks for the help jyk and Jingo :)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this