Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

C++: passing and returning char arrays to and from functions

Options
  • 13-08-2009 1:26pm
    #1
    Closed Accounts Posts: 356 ✭✭


    Okay I have a class something like this
    class SomeClass{
    	private:
                  char name[20];
    	public:
    	      void setName(char[]);
    	      char[] getName(); //i know this code is wrong
    }
    

    Basically I have a class with a character array as a private member variable. I want to be able to set and get this character array. Its been a while since I done some c++ so I am rusty and haven’t done a huge amount of c++ to begin with, Should I be using char * or would someone recommend I use string defined in <string> or how do I accomplish what I want using character arrays.


Comments

  • Closed Accounts Posts: 356 ✭✭Mullicker


    
    class SomeClass{
    	private:
                char* name;
    	public:
    		void setName(char* cptr){
                 name=cptr;
            }
    		char* getName(){
                  return name;
            }
            void showName(){cout<<name<<"\n";}
    };
    
    int main(int argc, char *argv[])
    {
        
        char* charptr = "dingle";
        cout<<charptr<<"\n";
        SomeClass Test;
        Test.setName(charptr);
        Test.showName();
        Test.setName("aha");
        charptr=Test.getName();
        cout<<charptr<<"\n";
        
        
        system("PAUSE");
        return EXIT_SUCCESS;
    }
    

    Never mind figured it out.


  • Closed Accounts Posts: 7,794 ✭✭✭JC 2K3


    Firstly, if you're using C++, why are you using C strings(i.e. character arrays)? C++ has its own string class.

    Secondly, if you must use C strings, that code is wrong. You're returning the address of 'name', i.e. if you call getName() and then modify what you've returned, you'll change the contents of 'name' in the object itself. You want to do something like:
    char* getName()
    {
      return strdup (name);
    }
    

    Which will copy 'name' to a different memory location and return that address.


Advertisement