Hi guys, I have a problem with a program:
#include <iostream>
#include <string>
using namespace std ;
// Uses a class with "public" member variables, so directly accessible
class Student
{
public :
string name ;
int reg ;
} ;
int main( )
{
const char NL = '\n' ;
const int LINE_LENGTH = 80 ;
const int NUM_STUDENTS = 3 ;
Student studentSet[ NUM_STUDENTS ] ;
cout << "For the set of students "
<< endl ;
for ( int i = 0 ; i < NUM_STUDENTS ; i++ )
{
cout << "Enter the name of student number "
<< i + 1
<< ": " ;
getline( cin, studentSet[ i] . name ) ;
cout << "Enter this student's registration ID: " ;
cin >> studentSet[ i ] . reg ;
cin . ignore( LINE_LENGTH, NL ) ;
cout << endl ;
}
//cout<<"Address " << &studentSet[0]<< &studentSet[1] << &studentSet[2] << &studentSet[3];
for ( Student* student_ptr = studentSet ;
student_ptr < &studentSet[ NUM_STUDENTS ] ;
student_ptr++ )
{
cout << "Name of a student: "
<< student_ptr -> name
<< endl ;
cout << "Student registration ID: "
<< student_ptr -> reg
<< endl
<< endl ;
}
}
My problem is with the pointer in the loop
for ( Student* student_ptr = studentSet ;
student_ptr < &studentSet[ NUM_STUDENTS ] ;
student_ptr++ )
Now, I am trying to get my head around pointers, and I must admit that I am finding it difficult. Let me run through the loop and see if I get everything right.Student* student_ptr = studentSet ;
creates a pointer student_ptr
which will point to studentSet[0];
now, here is the problem: student_ptr < &studentSet[ NUM_STUDENTS ] ;
is saying that the address of student_ptr
is < than the address of what? the address of the whole &studentSet[ NUM_STUDENTS ]
array (is it possible???) or the address of studentSet[2]
? as you can see I tried to display the addresses of all the elements of the array studentSet[ NUM_STUDENTS ]
but no joy. Also what is tricking me is the fact that it says student_ptr < &studentSet[ NUM_STUDENTS ] ;
. I thought that this is equivalent to student_ptr < &studentSet[ 3 ] ;
because NUM_STUDENTS = 3
, but if I replace NUM_STUDENTS
with 3 the program (I use visual C++ as a compiler) compiles fine but it returns bad pointer, which is fair enough because if I say
for ( Student* student_ptr = studentSet ;
student_ptr < &studentSet[ 3 ] ;
student_ptr++ )
I am trying to access studentSet[3]
which is out of range.
Hope it is clear...any suggestion?
thanks