When a get function has to return an array of char's , would i...?

Started by
8 comments, last by johnnyBravo 19 years, 4 months ago
Hi, I'm just wondering when I have say something like: char name[10]; or char* name = new char[10]; or char name[] = "Joe"; how would I write the get function for it, like if im in a class. eg would it be char* getName(); or something else? As I've heard stuff about not supposed to be using char* for strings. If anyone could explain that, or know of a website that explains it, thanks
Advertisement
You have to be very careful about where the memory for the String is allocated and deallocated (new and delete).

All of the methods you have created the string there can be referenced as a char*. If the string is created as a local variable array in your get method, then the address that is returned with the char* will be invalid once the get method has executed. If the string is a member variable of the class, it will still be valid, but you must be sure that the class still exists as long as the char* is used.

If you use "new" within the get method and return the address of the memory it allocates, then you must free that memory elsewhere in your program so as you do not get a memory leak.

I would also recommend using "const" wherever possible (and useful) so that you don't change things you don't want to.

Example:

const char* getName() const;

This means that the getName method will not modify member variables and that the calling method promises not to change the string it will return.

-Rob
There are two 'good' ways to return strings in C++: The best method is to use a string class of some kind that takes care of copying and managing memory for you etc so you can't really screw it up.
The other way is to make the function take a character pointer and buffer length and copy the string to that buffer, like so:
bool getName(char *Buffer, size_t BufferLength){    size_t Length = Min(NameLength, BufferLength);    strncpy(Buffer, Name, Length);    //strncpy doesn't put a terminating \0 if the string is longer than Length    Buffer[Length-1] = 0;    return (BufferLength == NameLength) || (Min != BufferLength);}
The function returns true if BufferLength was long enough to hold the whole name, and false if it had to be cut short. You'd probably want to add tests to make sure the pointer is not null, buffer length is > 0, etc.
"Walk not the trodden path, for it has borne it's burden." -John, Flying Monk
If you return an array, return a CONST pointer, so the user can't change the data in the array.

Here's an example (look at the "get" function):

template< class T >class Array {  public:    Array() { size_ = 0; data_ = 0; }    ~Array() { delete[] data_; }    Array( Array const & o ) {      data_ = 0; set( o.data_, o.size_ );    }    Array & operator=( Array & o ) {      delete[] data_; set( o.data_, o.size_ );    }    void set( T const * ptr, size_t s ) {      delete[] data_;      data_ = new T;<br>      std::copy( ptr, ptr+s, data_ );<br>      size_ = s;<br>    }<br>    T const * get() const {<br>      return data_;<br>    }<br>    size_t size() const {<br>      return size_;<br>    }<br>  protected:<br>    T * data_;<br>    size_t size_;<br>};<br></pre><br><br>
enum Bool { True, False, FileNotFound };
Well right now I'm using the std::string class,
as I rather do a return "eg string getname();" type function, i guess i should just use the string class.

Its just that this is for my common classes eg cwindow, capp etc that i use everywhere i thought it might be better to use minimum external headers, and that string class might be a little slower than using dynamic arraylists
Quote:Premature optimization is the root of all evil.
--God has paid us the intolerable compliment of loving us, in the deepest, most tragic, most inexorable sense.- C.S. Lewis
Quote:Original post by antareus
Quote:Premature optimization is the root of all evil.


why is that?
Quote:Original post by johnnyBravo
Quote:Original post by antareus
Quote:Premature optimization is the root of all evil.


why is that?
Because 99.9999% of the time you'll optimize things that don't need optimizing at all and waste tons of time on acomplishing nothing when you could be getting your project to work.
You should always work on getting your program working with the right algorithms, and THEN profile and optimize what needs to be faster/smaller/etc. That way you won't waste time doing tons of work that doesn't need to be done.
"Walk not the trodden path, for it has borne it's burden." -John, Flying Monk
The thing you need to be aware of, is that idiots can call delete[] on a const pointer returned by a function. I guess it all comes down to how much idiot-proofing you want to implement. But if the code is for your own use, and know that you won't make that mistake, go for it.

Edit: Extrarius's method is an example of pure idiot proofism =P
I see, thanks

This topic is closed to new replies.

Advertisement