不知道是什么原因
#include<iostream>
using namespace std;
typedef struct
{
int year;
int month;
int date;
int hour;
int minute;
int second;
int millisecond;
}CALENDAR;
CALENDAR *getCalendar()
{
CALENDAR cal ;
cal.year = 2015;
cal.month = 8;
cal.date = 15;
cal.hour = 14;
cal.minute = 34;
cal.second = 23;
cal.millisecond = 123;
return &cal;
}
int main()
{
CALENDAR calendar;
CALENDAR* cal;
cal = getCalendar();
memcpy(&calendar, cal, sizeof(CALENDAR));
cout << calendar.year << " "
<< calendar.month << " "
<< calendar.date << " "
<< calendar.hour << " "
<< calendar.minute << " "
<< calendar.second << " "
<< calendar.millisecond << " "
<< sizeof(CALENDAR) << endl;
}
输出是这样的
怪我咯2017-04-17 12:05:19
局部變數CALENDAR cal ;是在堆疊上定義的,在退出函數作用域時就記憶體就釋放掉了,後續的程式碼將覆蓋這塊記憶體區域,輸出就是未確定的值;
CALENDAR getCalendar()
{
CALENDAR cal ;
cal.year = 2015;
cal.month = 8;
cal.date = 15;
cal.minute = 34;
cal.second = 23;
cal.millisecond = 123;
return cal;
}
{
cal.year = 2015;
cal.month = 8;
cal.date = 15;
cal.
cal.second = 23;
cal.millisecond = 123;
}
CALENDAR calendar;
getCalendar(cal}
CALENDAR calendar;
getCalendar(cal});