阐述
主函数中的结构体变量作为非主函数的参数时,若只是将结构体变量名传与非主函数, 那就意味着仅是将其值传递给了非主函数内部,相当于在非主函数内部复制粘贴了一个新的结构体(此处称之为X),这个新结构体X与主函数中的结构体(此处称之为Y)是相互独立的,但它们二者的初始成员值都相同.
struct SSS{
...
};
void NonMain(SSS X){
// X & Y的初始成员值都相同, 地址却相异
...
}
int main(){
SSS Y;
NonMain(Y);
return 0;
}
根据上述代码,如果在NonMain函数中改变了结构体变量内部的值,当NonMain函数运行结束后,程序返回主函数时,主函数中原有的结构体变量内部不会有丝毫变化.
这是因为结构体变量名本身不是地址, 非主函数内所操作的结构体变量的地址,并非主函数中的结构体变量的地址.
因此,正确的结构体变量传参与非主函数时,需要先取出结构体变量的地址当作指针,再将指针传与非主函数.
代码示例
#include <string>
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
typedef struct TimesRecord
{
int year;
int month;
int day;
} times;
void initializationError(TimesRecord date_record)
{
date_record.year = 2015;
date_record.month = 5;
date_record.day = 18;
cout << "initializationError.&date_record: " << &date_record << endl;
}
void alterError(TimesRecord date_record, int newYear, int newMonth, int newDay)
{
date_record.year = newYear;
date_record.month = newMonth;
date_record.day = newDay;
cout << "alterError.&date_record: " << &date_record << endl;
}
/* ----------------------------------------------------------------------------- */
void initializationCorrect(TimesRecord &date_record)
{
date_record.year = 2015;
date_record.month = 5;
date_record.day = 18;
cout << "initializationCorrect.&date_record: " << &date_record << endl;
}
void alterCorrect(TimesRecord &date_record, int newYear, int newMonth, int newDay)
{
date_record.year = newYear;
date_record.month = newMonth;
date_record.day = newDay;
cout << "alterCorrect.&date_record: " << &date_record << endl;
}
int main(int argc, char const *argv[])
{
TimesRecord t;
int newYear = 2006;
int newMonth = 9;
int newDay = 22;
initializationError(t);
cout << "Error initialization: ";
cout << t.year << "-" << t.month << "-" << t.day << endl;
cout << "main.&t: " << &t << endl;
cout << endl;
alterError(t, newYear, newMonth, newDay);
cout << "Error Alter: ";
cout << t.year << "-" << t.month << "-" << t.day << endl;
cout << "main.&t: " << &t << endl;
cout << endl;
initializationCorrect(t);
cout << "Correct initialization: ";
cout << t.year << "-" << t.month << "-" << t.day << endl;
cout << "main.&t: " << &t << endl;
cout << endl;
alterCorrect(t, newYear, newMonth, newDay);
cout << "Correct Alter: ";
cout << t.year << "-" << t.month << "-" << t.day << endl;
cout << "main.&t: " << &t << endl;
return 0;
}
运行结果
initializationError.&date_record: 0x7ffc498004b0
Error initialization: -5234528-22046-1233126896
main.&t: 0x7ffc498004e8
alterError.&date_record: 0x7ffc498004b0
Error Alter: -5234528-22046-1233126896
main.&t: 0x7ffc498004e8
initializationCorrect.&date_record: 0x7ffc498004e8
Correct initialization: 2015-5-18
main.&t: 0x7ffc498004e8
alterCorrect.&date_record: 0x7ffc498004e8
Correct Alter: 2006-9-22
main.&t: 0x7ffc498004e8
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。