0

When using some library functions (e.g. strftime(), strcpy(), MultiByteToWideChar()) that deal with character arrays (instead of std::string's) one has 2 options:

  • use a fixed size array (e.g. char buffer[256];) which is obviously bad because of the string length limit
  • use new to allocate required size which is also bad when one wants to create a utility function like this:

    char * fun(void)
    {
        char * array = new char[exact_required_size];
        some_function(array);
        return array;
    }
    

    because the user of such function has to delete the array.

And the 2nd option isn't even always possible if one can't know the exact array size/length before using the problematic function (when one can't predict how long a string the function will return).

The perfect way would be to use std::string since it has variable length and its destructor takes care of deallocating memory but many library functions just don't support std::string (whether they should is another question).

Ok, so what's the problem? Well - how should I use these functions? Use a fixed size array or use new and make the user of my function worry about deallocating memory? Or maybe there actually is a smooth solution I didn't think of?

NPS
  • 6,003
  • 11
  • 53
  • 90

1 Answers1

0

You can use std::string's data() method to get a pointer to a character array with the same sequence of characters currently contained in the string object. The character pointer returned points to a constant, non-modifiable character array located somewhere in internal memory. You don't need to worry about deallocating the memory referenced by this pointer as the string object's destructor will do so automatically.

But as to your original question: depends on how you want the function to work. If you're modifying a character array that you create within the function, it sounds like you'll need to allocate memory on the heap and return a pointer to it. The user would have to deallocate the memory themselves - there are plenty of standard library functions that work this way.

Alternatively, you could force the user to pass in character pointer as a parameter, which would ensure they've already created the array and know that they will need to deallocate the memory themselves. That method is used even more often and is probably preferable.

Alex Kalicki
  • 1,533
  • 9
  • 20
  • I'm not sure if I understood - you say I could do sth like this: `std::string buffer; strcpy (buffer.data(), "text");`? – NPS May 02 '13 at 23:35