gpt4 book ai didi

结构中带有变量的cout的c++顺序会更改内容吗?

转载 作者:行者123 更新时间:2023-11-28 00:13:22 25 4
gpt4 key购买 nike

<分区>

我遇到了一个奇怪的问题。我有一个带指针的练习,根据 cout 语句的顺序,结果会有所不同。根据我首先计算的两个结构变量,它们的结果不同。更具体地说, Student 结构有两个变量,name 和 gpa。设置变量后,如果我 cout gpa 然后 name,gpa 可以,而 name 不行;如果我 cout name 然后 gpa,name 是好的,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 顺序会影响结构变量的内容吗?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com