tags:

views:

145

answers:

3

Im passing function GetCurrentDate() the pointer to a tm struct.

Within that function I printf the uninitialized data, then the initialized. Expected results.

However when i return the tm struct appears uninitialized.

See console output bellow. What am i doing wrong?

uninitialized date:??? ???-1073908332 01:9448278:-1073908376 -1217355836

initialized date:Wed May 5 23:08:40 2010

Caller date:??? ???-1073908332 01:9448278:-1073908376 -121735583

int main()
{

 test(); 
}

int test()
{


    struct tm* CurrentDate;

    GetCurrentDate(CurrentDate);

    printf("Caller date:%s\n",asctime (CurrentDate));

    return 1;
}


int GetCurrentDate(struct tm* p_ReturnDate)
{ 
 printf("uninitialized date:%s\n",asctime (p_ReturnDate));
 time_t m_TimeEntity;
 m_TimeEntity = time(NULL); //setting current time into a time_t struct

 p_ReturnDate = localtime(&m_TimeEntity); //converting time_t to tm struct
 printf("initialized date:%s\n",asctime (p_ReturnDate));
 return 1;
}  
+6  A: 

You are updating the pointer p_ReturnDate in the function, not updating the structure that p_ReturnDate points to. Because the pointer is passed by value, the update doesn't affect the caller.

Also as pointed out by Joseph Quinsey you need to provide a place to put the result. You're only allocating a pointer in the caller, not the whole structure.

Mark Ransom
+5  A: 

In test(), you need to actually specify memory to store the data. For example;

struct tm CurrentDate;
GetCurrentDate(&CurrentDate);
printf("Caller date:%s\n",asctime(&CurrentDate));
Joseph Quinsey
this does not work
Luke Mcneice
Yes, the dreaded two-bug design pattern, as Mark Ranson points out.
Joseph Quinsey
"The dreaded two-bug design pattern" - that's great, I'll have to remember that one! I'm surprised the GOF didn't cover it in their book, it's popular enough.
Mark Ransom
+1  A: 
int
main()
{
    test(); 
}

void
test()
{
    struct tm CurrentDate;

    GetCurrentDate(&CurrentDate);
    printf("Caller date:%s\n", asctime(&CurrentDate));
}

void
GetCurrentDate(struct tm* p_ReturnDate)
{ 
    time_t m_TimeEntity;

    printf("uninitialized date:%s\n", asctime(p_ReturnDate));    
    m_TimeEntity = time(NULL); //setting current time into a time_t struct
    *p_ReturnDate = *localtime(&m_TimeEntity); //converting time_t to tm struct    
    printf("initialized date:%s\n", asctime (p_ReturnDate));
}  
Judge Maygarden
Sometimes it's best to let someone figure things out on their own. Sometimes they need to see the answer before they can understand. It's a fine line.
Mark Ransom