我正在向函数GetCurrentDate()
传递指向tm结构的指针。在该函数中,我打印未初始化的数据,然后初始化。预期结果。
然而,当我返回时,tm结构显示为未初始化。请参阅下面的控制台输我做错了什么?
未初始化的日期:??? ??? - 1073908332 01:9448278:-1073908376 -1217355836
初始化日期:5月5日星期三23:08:40 2010
来电日期:??? ??? - 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;
}
答案 0 :(得分:6)
您正在更新函数中的指针p_ReturnDate,而不是更新p_ReturnDate指向的结构。因为指针是按值传递的,所以更新不会影响调用者。
同样如Joseph Quinsey所指出,你需要提供一个放置结果的地方。你只是在调用者中分配一个指针,而不是整个结构。
答案 1 :(得分:5)
在test()中,您需要实际指定用于存储数据的内存。例如;
struct tm CurrentDate;
GetCurrentDate(&CurrentDate);
printf("Caller date:%s\n",asctime(&CurrentDate));
答案 2 :(得分:1)
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));
}