[英]Passing pointer into function, data appears initialized in function, on return appears uninitialized
我正在传递函数GetCurrentDate()
指向tm结构的指针。 在该函数中,我先打印未初始化的数据,然后再进行初始化。 预期成绩。
但是,当我返回时,tm结构似乎未初始化。 请参阅下面的控制台输出。 我究竟做错了什么?
未初始化的日期:??? ???-1073908332 01:9448278:-1073908376 -1217355836
初始化日期:2010年5月5日星期三23:08:40
来电者日期:??? ???-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;
}
您正在更新函数中的指针p_ReturnDate,而不是更新p_ReturnDate指向的结构。 由于指针是按值传递的,因此更新不会影响调用方。
同样,正如Joseph Quinsey指出的那样,您需要提供一个放置结果的地方。 您只在调用方中分配了一个指针,而不是整个结构。
在test()中,您需要实际指定用于存储数据的内存。 例如;
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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.