I'm having an odd problem. I have a practice exercise with pointers and the results are coming out differently depending on the order of cout statements. Depending on of the two struct variables I cout first, they come out differently. More specifically, the struct Student has two variables, name and gpa. After setting up the variables, if I cout gpa then name, gpa is fine and name is not; if I cout name then gpa, name is fine and gpa is not. Any idea why?
This is the code, with name then gpa output:
#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
}
My output:
Student name is fubar
Student gpa is 0.00
If I reverse the cout statements, the output is
Student gpa is 4.00
Student name is
Any idea why the cout order is affecting the content of the struct variables?