Thread: multiple (ctime) struct tm* objects

  1. #1
    Registered User
    Join Date
    May 2003
    Posts
    38

    multiple (ctime) struct tm* objects

    I would like to store multiple "struct tm*" time data objects in a data class. These object would need to hold different times (lets say a start time, and an end time). But it seems like anytime I modify one of the objects they both change. How do I work around this?

    (i can insert example code if needed)
    chris

  2. #2
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    please post code.

  3. #3
    Registered User
    Join Date
    May 2003
    Posts
    38

    code

    Code:
    time_t now;
    struct tm *tm_now;
    struct tm *tm_later;
    
    now      = time ( NULL );
    tm_now   = localtime ( &now );
    tm_later = localtime ( &now );
    
    tm_later->tm_hour = 12;
    
    printf ( "%s", asctime ( tm_now ) );
    printf ( "%s", asctime ( tm_later ) );
    This isn't the actual code, but it is an example of what I am talking about. How can I make tm_now, and tm_later have different times?
    chris

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Read the manual

    Code:
    NOTES
           The four functions acstime(), ctime(), gmtime() and localtime()  return
           a  pointer  to  static data and hence are not thread‐safe.
    Since localtime() returns a pointer to static data, you can only use one at one, unless you save the result elsewhere

    Code:
    time_t now;
    struct tm tm_now;
    struct tm tm_later;
    
    now      = time ( NULL );
    tm_now   = *localtime ( &now );
    tm_later = *localtime ( &now );
    
    tm_later.tm_hour = 12;
    
    printf ( "%s", asctime ( &tm_now ) );
    printf ( "%s", asctime ( &tm_later ) );
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Parsing Struct Objects to Threads
    By pobri19 in forum C Programming
    Replies: 4
    Last Post: 04-18-2009, 06:25 AM
  2. Assignment HELP!!
    By cprogrammer22 in forum C Programming
    Replies: 35
    Last Post: 01-24-2009, 02:24 PM
  3. What's wrong with my search program?
    By sherwi in forum C Programming
    Replies: 5
    Last Post: 04-28-2006, 09:57 AM
  4. Function validation.
    By Fhl in forum C Programming
    Replies: 10
    Last Post: 02-22-2006, 08:18 AM
  5. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM