为什么memcpy(calendar, cal, sizeof(CALENDAR))这里输出是错误的啊,搞不懂了

不知道是什么原因

#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;

}

输出是这样的
图片描述

回答:

局部变量CALENDAR cal ;是在栈上定义的,在退出函数作用域时就内存就释放掉了,后续的代码将覆盖这块内存区域,输出就是未确定的值;

可以改用直接返回对象而非指针

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;
}

也可以改用引用(或指针)传入返回;

void getCalendar(CALENDAR& cal)
{
cal.year = 2015;
cal.month = 8;
cal.date = 15;
cal.hour = 14;
cal.minute = 34;
cal.second = 23;
cal.millisecond = 123;
}
CALENDAR calendar;
getCalendar(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; // 返回局部变量的引用 闹哪样?

}

以上是 为什么memcpy(calendar, cal, sizeof(CALENDAR))这里输出是错误的啊,搞不懂了 的全部内容, 来源链接: utcz.com/p/193174.html

回到顶部