Char array size when using certain library functions -
when using library functions (e.g. strftime()
, strcpy()
, multibytetowidechar()
) deal character arrays (instead of std::string
's) 1 has 2 options:
- use fixed size array (e.g.
char buffer[256];
) bad because of string length limit use
new
allocate required size bad when 1 wants create utility function this:char * fun(void) { char * array = new char[exact_required_size]; some_function(array); return array; }
because user of such function has
delete
array
.
and 2nd option isn't possible if 1 can't know exact array size/length before using problematic function (when 1 can't predict how long string function return).
the perfect way use std::string
since has variable length , destructor takes care of deallocating memory many library functions don't support std::string
(whether should question).
ok, what's problem? - how should use these functions? use fixed size array or use new
, make user of function worry deallocating memory? or maybe there is smooth solution didn't think of?
you can use std::string
's data()
method pointer character array same sequence of characters contained in string
object. character pointer returned points constant, non-modifiable character array located somewhere in internal memory. don't need worry deallocating memory referenced pointer string
object's destructor automatically.
but original question: depends on how want function work. if you're modifying character array create within function, sounds you'll need allocate memory on heap , return pointer it. user have deallocate memory - there plenty of standard library functions work way.
alternatively, force user pass in character pointer parameter, ensure they've created array , know need deallocate memory themselves. method used more , preferable.
Comments
Post a Comment