Lab 5: Practice with structs, new, arrays, pointers and sorting
- Please go read Chapter 6.1 on structs - the tutorial here
may also help. Consider the following struct
struct student
{
char name[50];
double gradePointAverage;
};
Make sure you remember the semicolon at the end of the struct definition (missing it is a
common error)
- You can create and use one of these structs in your program with code like the following:
student ChrisFischer;
strcpy( ChrisFischer.name, "Chris Fischer" );
ChrisFischer.gradePointAverage = 99.9;
Note the use of the dot operator. The dot operator is what allows you to go "inside" the struct
and access the individual pieces.
- You can also make a pointer this structure, like this:
student* ChrisFischerPtr;
ChrisFischerPtr = & ChrisFischer;
and access it like this:
strcpy( ( *ChrisFischerPtr ).name, "Chris Fischer" );
( *ChrisFischerPtr ).gradePointAverage = 99.9;
- But the far better way of doing this is with the new operator.
student* ChrisFischerPtr = new student;
strcpy( ( *ChrisFischerPtr ).name, "Chris Fischer" );
( *ChrisFischerPtr ).gradePointAverage = 99.9;
- You can also make arrays of pointers, like the following:
const int CLASS_SIZE = 5;
student* classArray[ CLASS_SIZE ];
for ( int i = 0; i < CLASS_SIZE; i ++ )
{
classArray[ i ] = new student;
( *classArray[ i ] ).gradePointAverage = 99.9; //get this from somewhere else
strcpy( ( *classArray[ i ] ).name, "Some Name" ); //get name from somewhere
}
for ( int i = 0; i < CLASS_SIZE; i ++ )
{
cout << "Student #" << i << "Name: " << ( *classArray[ i ] ).name
<<" GPA: "<< ( *classArray[ i ] ).gradePointAverage <<endl;
}
So why make an array of pointers? Why not just a normal array? Because with pointers,
swapping two positions in an array becomes as simple as moving pointers since you can make a simple
swap function to do it (HINT: YOU ALREADY HAVE.)
Assignment:
Using the above student struct, create a short program that creates an array of pointers to student objects.
Input a reasonable amount of students, say 5 or 6, using something like the above way of doing it
(taking input from the keyboard is fine.) Then, after your array is created and you've inputted all the
students, you should print out the array, sorted by highest GPA, is some neat fashion.