我對C++很新,需要一些關於下面代碼的幫助。返回一個結構指針
#include <iostream>
using namespace std;
struct student {
string name;
int age;
float marks;
};
struct student *initiateStudent(string , int , float);
int main () {
int totalStudents = 1;
string name;
int age;
float marks;
cin >> totalStudents;
student *stud[totalStudents];
for(int i = 0; i < totalStudents; i++) {
cin >> name >> age >> marks;
stud[i] = initiateStudent(name,age,marks);
}
cout << stud[0]->name;
return 0;
}
struct student *initiateStudent(string name, int age, float marks)
{
student *temp_student;
temp_student->name = name;
temp_student->age = age;
temp_student->marks = marks;
return temp_student;
}
我需要在功能initiateStudent通過將會員名,年齡,標記一個結構指針返回指針數組螺柱。 我知道問題的根源在於,當我返回到主文件時temp_student被銷燬。 所以我的問題是如何通過傳遞結構的成員,然後返回信息返回到指針數組螺柱。
非常感謝。
'student * temp_student;'錯過了分配:您在這裏有未定義的行爲。 –
您正在使用哪本書來學習C++?你似乎已經撿到了一些壞習慣:( –
'code.c:10:3:警告 - 「學生」在代碼中發現 - 可能的星期天晚上的作業 - 當回答時預計downvoting :) :) –