我正在探索C ++中结构的所有可能性,当我谈到结构指针时,我遇到了一些运行时错误。
这是我的代码:
#include<iostream>
#include<string>
using namespace std;
// globally defined structure can be used in any method
struct stud
{
int roll;
string sname;
// nested structure for date of birth
struct dob
{
int date;
int month;
int year;
} dob1;
int marks1;
int marks2;
int marks3;
} stud1 = {1,"pranshu1",{11,4,1993},65,87,80};
// function to calculate average of a student
float calaverage(stud s1)
{
float savg=s1.marks1+s1.marks2+s1.marks3;
savg=savg/3;
return savg;
}
// function to calculate the average of whole class
// function parameter are the starting address of the array of the structure stud
// and the total no of elements in the array
float avgclass(stud *ptr, int no_of_stud)
{
float classtotal=0;
for(int i=0;i<no_of_stud; i++)
{
classtotal=classtotal+calaverage(*(ptr+i));
}
return classtotal;
}
int main()
{
// array of structure
struct stud class1[3]=
{
stud1,
{2,"pranshu2",{11,4,1993},80,95},
{3,"pranshu3",{11,4,1993},64,84,93}
};
// initializing the value by accessing the member
class1[0].marks3=93;
struct stud* stud5;
stud5->roll=10;
stud5->sname="pranshu";
stud5->dob1.date=11;
stud5->dob1.month=4;
stud5->dob1.year=93;
stud5->marks1=97;
stud5->marks2=45;
stud5->marks3=98;
cout<<stud5->roll<<endl;
// average marks of student 1
cout<<"Average marks of "<<stud1.sname<<" with roll no "<<stud1.roll<<" is "<<calaverage(stud1)<<endl;
// class average
cout<<"Class average is "<<avgclass(class1,3)<<endl;
}
错误与stud5有关,但我没有得到任何关于它的线索..
答案 0 :(得分:1)
struct stud* stud5;
只是一个指针......你还应该分配内存:
stud5 = new stud;
拥有一个物体。