Can function return an array?

This is a discussion on Can function return an array? within the C++ Programming forums, part of the General Programming Boards category; In a member function of my class I made a string array. In a different member function (same class) I ...

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    17

    Can function return an array?

    In a member function of my class I made a string array. In a different member function (same class) I need to be able to read that array. I did a quick search here and didn't find anything, google was hinting that I needed to use a pointer??

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Technically, you can return an array from a function, but 99% of the cases where this is asked, the CORRECT thing to do is to pass in an array, modify that array, rather than returning an array, so unless you have a VERY specific reason to return an array from a function, that would be my suggestion. The reason for this suggestion is that most of the time someone wants to return an array, that is returning a local variable array - which makes no little sense.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Apr 2008
    Posts
    890
    Quote Originally Posted by bulletbutter View Post
    In a member function of my class I made a string array. In a different member function (same class) I need to be able to read that array. I did a quick search here and didn't find anything, google was hinting that I needed to use a pointer??
    What do you mean "string array"? An array of std::string objects, or a char []? What is this string array used for?

  4. #4
    Registered User
    Join Date
    Apr 2008
    Posts
    17
    Well I am kinda brainstorming this whole thing so I will just post the parts of the code I have....I know its messy and prolly wont compile but I am just trying to get it down on paper before I hit the compiler...

    This is the class
    Code:
    class Mobs { 
    		public:
    		            string getMobState(); // random roll to decide if its caster or melee
    			void getMobColor(); // random roll to get mobs color (difficulty)
    			void getMobName(); // caster name if its a caster or a melee name if its melee
    			int getStats(); // stats refer to hit points and mana
    			string getAbilities(); // string array
    			?? runMobScript(); // not sure what the return type should be...will decide what spells are cast
    			void CastSpell(); // code for castig spell, returns text about what happened
    			int meleeDamage; // how hard the mob physically hits
    		private:
    			int mobMaxHP; // mobs hitpoints
    			int mobMaxMP; // mobs mana
    			string mobLocation(); // the mobs location
    			sting mobState; // caster or melee?
    			string mobName; // Sets mobs name
    			string mobAbilities[]; // will be an array of strings
    			
    	       }
    This is the member function I need the array for. CastSpell() needs to be able to search through the array to find the list of mobAbilities.
    Code:
    ?? Mobs::runMobScript() {
    	If (mobName == “Troll Magician”) {
    	CastSpell(); // check to see if mob has mana, pick a random spell from abilities list and cast if
    		               Mob has the mana to cast it. If mob has no mana, melee hit
    And the member function where I need to return the array
    Code:
    string Mobs::getAbilities()
    {
    	if (mobState == caster && mobLocation == "troll bane cave") {
    	“Frostbolt”, “LighteningBolt”, “Firebolt”
    	// Place these spells in a string array??
    	}
    	If (mobState == melee && mobLocation == “troll bane cave”){
    	“Sunder”, “Fire Blade”, “Ice Blade”, “Lightening Blade”
    	// place these abilities in a string array??
    }
    	if (mobState == caster && mobLocation == "Orc Haven") {
    	“Frostbolt”, “LighteningBolt”, “Firebolt”, “FlameWalker”, “FlameWalker Nova”
    	// Place these spells in a string array??
    	}
    	If (mobState == melee && mobLocation == “Orc Haven”){
    	“Sunder”, “Fire Blade”, “Ice Blade”, “Lightening Blade”, “Bash”, Inpower”, “Hostile Charge”
    	// place these abilities in a string array??
    }
    	if (mobState == caster && mobLocation == "Ogre Den") {
    	“Frostbolt”, “LighteningBolt”, “Firebolt”, “FlameWalker”, “FlameWalker Nova”, “Cleanse”, “Reflect”, 
    	“WaterWalker”, “WaterWalker Nova”
    	// Place these spells in a string array??
    	}
    	If (mobState == melee && mobLocation == “Ogre Den”){
    	“Bash”, “Overpower”
    	// place these abilities in a string array??
    }
    Return mobAbilities[];
    
    }
    Last edited by bulletbutter; 04-17-2008 at 09:43 AM.

  5. #5
    Registered User
    Join Date
    Apr 2008
    Posts
    890
    Well, I would probably implement the multiple behaviors via mixins or the decorator pattern, but if you want to keep this design intact, make it a std::vector of std::string, and let the STL manage the allocation and copying. I'd be hard pressed to find a reason to use a variable length array instead of a vector or deque.

    Another thing you could do is use a simple bitmask to store behaviors (e.g. behavior |= ICE_BLADE).
    Last edited by medievalelks; 04-17-2008 at 09:54 AM.

  6. #6
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,614
    Returning arrays requires creating it on the heap and returning it which is messy. Therefore the usual way is taking an argument as mats says. But in C++, there's a better way. Just return a std::vector. If the code isn't too complex, the compiler will optimize away the make a copy of the vector process (unnamed variable optimization, NRVO or something I think it's called?).
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  7. #7
    Registered User
    Join Date
    Apr 2008
    Posts
    890
    Quote Originally Posted by Elysia View Post
    Returning arrays requires creating it on the heap and returning it which is messy.
    You could also declare a static array in the function, but again, std::vector is the superior solution.

  8. #8
    Registered User
    Join Date
    Apr 2006
    Posts
    2,036
    You can return mobAbilities as long as its a member variable. You'd actually be returning a pointer to the first element.

    It looks like this:
    Code:
    string *Mobs::getAbilities() 
    {
        return mobAbilities;
    }
    However, most likely, since you don't know what size the mobAbilities array needs to be for each Mob, you should use a vector instead of an array to store the information in the class. In that case returning that vector from a function should generally be done like so:
    Code:
    vector<string> &Mobs::getAbilities() 
    {
        return mobAbilities;
    }
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  9. #9
    Registered User
    Join Date
    Apr 2008
    Posts
    890
    Quote Originally Posted by King Mir View Post
    Code:
    vector<string> &Mobs::getAbilities() 
    {
        return mobAbilities;
    }
    Return by value, not reference. Otherwise the private member data is exposed and modifiable.

  10. #10
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,614
    Unless it's returned by a const reference.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  11. #11
    Registered User
    Join Date
    Apr 2008
    Posts
    890
    Quote Originally Posted by Elysia View Post
    Unless it's returned by a const reference.
    That's easy enough to get around.

    Code:
    #include <iostream>
    
    class unsafe {
        int i;
    public:
        unsafe(int) : i(j) {}
        const int & peek() { return i; }
    };
    
    int main()
    {
        unsafe u(5);
    
        std::cout << u.peek() << std::endl;
        int & i = (int &) u.peek();
        i++;
        std::cout << u.peek() << std::endl;
    
        return 0;
    }

  12. #12
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,614
    There are always workarounds. You can't protect against everything.
    If you return by const, then you've done right and the one who casts away the const does wrong.
    It's possible to do this another way, too:

    Code:
    #include <iostream>
    
    class unsafe {
        int i;
    public:
        unsafe(int) : i(j) {}
        const int & peek() { return i; }
    };
    
    int main()
    {
        unsafe u(5);
    
        std::cout << u.peek() << std::endl;
        int* i = (int*)&u;
        (*i)++;
        std::cout << u.peek() << std::endl;
    
        return 0;
    }
    So whether or not you return a reference, the data isn't "safe," regardless of what you do. You can only ensure it's right to such a degree.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  13. #13
    Registered User
    Join Date
    Apr 2006
    Posts
    2,036
    Yeah, const reference is best in this case. Should have put that in there.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  14. #14
    Registered User
    Join Date
    Apr 2006
    Posts
    2,036
    Quote Originally Posted by medievalelks View Post
    That's easy enough to get around.

    Code:
    #include <iostream>
    
    class unsafe {
        int i;
    public:
        unsafe(int) : i(j) {}
        const int & peek() { return i; }
    };
    
    int main()
    {
        unsafe u(5);
    
        std::cout << u.peek() << std::endl;
        int & i = (int &) u.peek();
        i++;
        std::cout << u.peek() << std::endl;
    
        return 0;
    }
    Sure. If the programmer wants to break his contract with himself, why stop him?

    It still eliminates the unnecessary copy.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  15. #15
    Registered User
    Join Date
    Apr 2008
    Posts
    890
    Quote Originally Posted by King Mir View Post
    Sure. If the programmer wants to break his contract with himself, why stop him?

    It still eliminates the unnecessary copy.
    I'd rather preserve encapsulation than prematurely optimize.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 02:07 AM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 01:53 AM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 09:33 AM
  5. qt help
    By Unregistered in forum Linux Programming
    Replies: 1
    Last Post: 04-20-2002, 09:51 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21