// Struct example - student record with a member function // (print member function) // #include // here we define the struct. // This tells the compiler about the new type StudentRecord, but // doesn't result in any variables being allocated memory. struct StudentRecord { char *name; // student name double hw[3]; // homework grades double test[2]; // test grades double ave; // final average void print() { cout << "Name: " << name << endl; for (int i=0;i<3;i++) cout << "HW #" << i << ": " << hw[i] << endl; for (int i=0;i<2;i++) cout << "TEST #" << i << ": " << test[i] << endl; cout << "Average: " << ave << endl; } }; // this won't work - the struct is passed by value, // so we get a copy (and the original will not be updated). // // NOTE: You can get this to work by changing the parameter to // be a reference parameter! void update_average( StudentRecord stu) { double tot=0; for (int i=0;i<3;i++) tot += stu.hw[i]; for (int i=0;i<3;i++) tot += stu.test[i]; stu.ave = tot/5; } // this will work - we use a pointer to a struct instead void update_average( StudentRecord *stu) { double tot=0; for (int i=0;i<3;i++) tot += stu->hw[i]; for (int i=0;i<3;i++) tot += stu->test[i]; stu->ave = tot/5; } int main(void) { // declare a variable of type StudentRecord StudentRecord stu; // initialize with some stuff stu.name = "Joe Student"; stu.hw[0] = 90.5; stu.hw[1] = 100; stu.hw[2] = 55.25; stu.test[0] = 82.5; stu.test[1] = 88; //print the record - note that we haven't set the average yet! stu.print(); // now call the bad average function (that doesn't work). update_average(stu); //print the stu - note that we still haven't set the average yet! stu.print(); // now try with a pointer update_average(&stu); //print the stu - note we now have an average stu.print(); return(0); }