Click to See Complete Forum and Search --> : char* return type alternative
link
September 18th, 2002, 08:17 AM
I know the following is poor, but thats why im posting. This is what i have...
char* myFunc()
{
char* cTime;
struct tm *addedTime;
//...
strftime(cTime, 20, "%m/%d/%y %H:%M:%S", addedTime);
return cTime;
}
So cTime is not initialized properly and causes problems. Ive thought about using new, but how do i delete after returning? So what is the proper way? my knowledge of stl and string containers and such is poor.
Thx.
PaulWendt
September 18th, 2002, 08:51 AM
Can you return a std::string?
If not, make cTime a static char*. At least the data will still be
around once the function-call is over [even if it's not totally
thread-safe].
--Paul
dimm_coder
September 18th, 2002, 08:58 AM
heh... What problem.
You mast give memory for cTime:
char* myFunc()
{
char* cTime = new char[128];
struct tm *addedTime;
//...
strftime(cTime, 128, "%m/%d/%y %H:%M:%S", addedTime);
return cTime;
}
use it in main code:
char * ptr = myFunc();
...
delete [] ptr;
but it's not good maner of programming
Better:
bool myFunc(char * str, int nSize)
{
struct tm *addedTime;
//...
strftime(str, nSize, "%m/%d/%y %H:%M:%S", addedTime);
return cTime;
}
and use it
char str[128];
myFunc( str, 128 );
then str has formated string of time.
link
September 18th, 2002, 09:01 AM
Excellent. Thx both.
PaulWendt
September 18th, 2002, 09:42 AM
Oh. In my suggestion, I neglected to notice that you didn't
allocate storage in your function. If you use a character array local
to that function, make it static when you return it. Using a char*
passed in as an argument is better [in my opinion].
Over all solutions, I'd prefer std::string, though. You won't have
to worry about a buffer overrun or anything [at the slight cost
of performance, which you probably won't even notice anyway].
--Paul
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.