동적으로 생성 된 Course 배열을 사용하여 수행해야하는 클래스 할당입니다. 내 for 루프의 내부에서 각 멤버 변수를 읽으려고하는데 실제로 어떻게해야하는지 잘 모르겠습니다. 내 학생 구조와 함께 해봤지만,이 배열의 차이점은 내가 어떻게 진행해야할지 모르므로 나를 괴롭 히고있다.동적으로 생성 된 구조체의 배열에 대한 포인터 읽기
구조체 멤버를 읽을 때 readCourseArray
함수에 문제가 있습니다. 누구든지 내가 어떻게하는지 말해 줄 수 있다면 감사 할 것입니다. 나는 new
연산자를 사용하여 포인터의 많은 불필요한 존재와 함께 이상적인 것이 아니라 내 강사가있는 걸까요 할 할당을 필요로 얼마나 알고있다.
#include <iostream>
#include <string>
using namespace std;
struct Student
{
string firstName, lastName, aNumber;
double GPA;
};
struct Course
{
int courseNumber, creditHours;
string courseName;
char grade;
};
Student* readStudent();
Course* readCourseArray(int);
int main()
{
int courses = 0;
Student *studentPTR = readStudent();
Course *coursePTR = readCourseArray(courses);
delete studentPTR;
delete coursePTR;
system ("pause");
return 0;
}
Student* readStudent()
{ Student* student = new Student;
cout<<"\nEnter students first name\n";
cin>>student->firstName;
cout<<"\nEnter students last name\n";
cin>>student->lastName;
cout<<"\nEnter students A-Number\n";
cin>>student->aNumber;
return student;
}
Course* readCourseArray(int courses)
{
cout<<"\nHow many courses is the student taking?\n";
cin>>courses;
const int *sizePTR = &courses;
Course *coursePTR = new Course[*sizePTR];
for(int count = 0; count < *sizePTR; count++) //Enter course information
{
cout<<"\nEnter student "<<count<<"'s course name\n";
cin>>coursePTR[count]->courseName>>endl;
cout<<"\nEnter student "<<count<<"'s course number\n";
cin>>coursePTR[count]->courseNumber;
cout<<"\nEnter student "<<count<<"'s credit hours\n";
cin>>coursePTR[count]->creditHours;
cout<<"\nEnter student "<<count<<"'s grade\n";
cin>>coursePTR[count]->grade>>endl;
}
return coursePTR;
}
즉각적인 사실은 포인터를 반환하는 함수에서 로컬 변수를 반환하면 안된다는 것입니다. 함수에서 포인터를 만들면 함수가 끝나면 범위를 벗어나서 현재 죽은 데이터를 사용하려고 할 때 문제가 발생합니다. 'cin'을 사용하여 변수를 읽을 때,'coursePTR [count]'는 일반적인 변수처럼 취급되기 때문에'. 연산자'. 'coursePTR'에 화살표를 사용하십시오. 'coursePTR [count]'가'* (coursePTR + count)'로 읽혀지기 때문에'coursePTR [count]'는 이미 참조 해제되어 있습니다. – chris