CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Dec 2000
    Location
    Canada
    Posts
    732

    char* return type alternative

    I know the following is poor, but thats why im posting. This is what i have...
    Code:
    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.

  2. #2
    Join Date
    May 2000
    Location
    Phoenix, AZ [USA]
    Posts
    1,347
    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

  3. #3
    Join Date
    Sep 2002
    Location
    Belarus - Tirol, Austria
    Posts
    647
    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.

  4. #4
    Join Date
    Dec 2000
    Location
    Canada
    Posts
    732
    Excellent. Thx both.

  5. #5
    Join Date
    May 2000
    Location
    Phoenix, AZ [USA]
    Posts
    1,347
    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured