c++ - 为什么memcpy(calendar, cal, sizeof(CALENDAR))这里输出是错误的啊,搞不懂了
大家讲道理
大家讲道理 2017-04-17 12:03:19
0
2
877

不知道是什么原因

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

输出是这样的

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
刘奇

The local variable CALENDAR cal; is defined on the stack, and the memory is released when exiting the function scope. Subsequent code will cover this memory area, and the output is an undetermined value;

You can instead return objects directly instead of pointers

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

You can also use a reference (or pointer) to pass in and return;

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; // 返回局部变量的引用 闹哪样?
}

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!