我有一个奇怪的问题。我有一个带指针的练习练习,结果根据cout语句的顺序而有所不同。根据我首先考虑的两个结构变量,它们的出现方式不同。更具体地说,struct Student有两个变量,name和gpa。设置变量之后,如果我cout gpa然后命名,gpa很好,名字不是;如果我的名字然后gpa,名字很好,而gpa不是。知道为什么吗?
这是代码,名称为gpa输出:
#include <iostream>
#include <iomanip>
using namespace std;
struct Student
{
char * name;
float gpa;
};
Student *createStudent(char name[], float gpa);
int main()
{
int MAX = 100;
float stuGpa = 0;
char *stuName = new char[MAX];
cout << fixed << setprecision(2);
stuName = "fubar";
stuGpa = 4.0;
Student *student1;
student1 = new Student;
student1 = createStudent(stuName, stuGpa);
// cout name (first)
cout << "\nStudent name is " << student1->name;
// cout gpa (second)
cout << "\nStudent gpa is " << student1->gpa;
return 0;
}
Student *createStudent(char name[], float gpa)
{
int length = strlen(name);
Student newStudent;
newStudent.gpa = gpa;
newStudent.name = new char[length];
newStudent.name = name;
return &newStudent; //return the address of the newly created student
}
我的输出:
Student name is fubar
Student gpa is 0.00
如果我反转cout语句,则输出为
Student gpa is 4.00
Student name is
知道为什么cout顺序会影响struct变量的内容吗?
答案 0 :(得分:3)
是的,您要返回本地变量的地址:
Student *createStudent(char name[], float gpa)
{
Student newStudent; // <-------- here
return &newStudent; //return the address of the newly created student
}
只要createStudent
函数正在执行,新创建的学生才会生活。到达}
时会被破坏。您返回了指向不再存在的对象的指针。
主函数中也有内存泄漏:
student1 = new Student; // point "student1" to a newly allocated Student
student1 = createStudent(stuName, stuGpa); // point it elsewhere
&#34; new&#34;创建的对象不再有任何指示,因为你做了#34; student1&#34;指向别处。
还有另一个这样的泄漏:
stuName = new char[MAX]; // point stuName at some allocated memory
stuName = "fubar"; // point stuName at "fubar" instead
这是使用指针和new
时遇到的混乱。
要解决此问题,您最好的选择是进行以下更改:
Student
,而不是Student *
Student
,而不是Student *
char * name
更改为std::string name
char *stuName = new char[MAX];
更改为std::string stuName;