I'm 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 below. 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;
}
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.
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));
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));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.