Thread: How to access struct fields in array

  1. #1
    Registered User
    Join Date
    May 2002
    Posts
    85

    Question How to access struct fields in array

    Dear C++ experts out there,

    I am trying to access to array of struct data fields in a class.
    but compiler keep display error when access to struct fields.
    How class methods can access to the fields of a struct (array of struct) ?


    Code:
    struct StudentType
    {
       int age;
       char gender;
    };
    
    class StudentRecordHandler
    {
       public:
            StudentRecordHandler();
            void SetAge(int a);     //compile error
            int GetAge();              //compile error
            void SetGender(char gen);   //error
            char GetGender();                  // also error
            void SetRecordNumber(int RecNum);  // OK
            int GetRecordNumber();                     // OK
            //........
    
       private:
    
         StudentType stud[20];
         //additional data member for StudentRecordHandler
         int RecordNum,
         string Registrar;
    }
    Thank you very much for your help
    Last edited by dv007; 01-18-2006 at 09:15 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > StudentType[20];
    It's type name[size];

    So
    StudentType foo[20];

    To access an element, it would be
    foo[index].age = 42;

  3. #3
    Registered User
    Join Date
    May 2002
    Posts
    85
    Hi Salem,

    You mean accessing to data members of class (in this case is an array of struct) would be:
    Code:
    void SetAge(int a)
    {
        Stud[20].age = a;   // still error
    
    }

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Make your function part of the class then
    Code:
    void StudentRecordHandler::SetAge(int a)
    {
        Stud[20].age = a;   // still error
    }
    And 20 is outside the range of valid indices for an array declared as
    StudentType stud[20];

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Converting from C to C++
    By Taka in forum C++ Programming
    Replies: 5
    Last Post: 04-08-2009, 02:16 AM
  2. memory issue
    By t014y in forum C Programming
    Replies: 2
    Last Post: 02-21-2009, 12:37 AM
  3. Fixing my program
    By Mcwaffle in forum C Programming
    Replies: 5
    Last Post: 11-05-2008, 03:55 AM
  4. Array of struct pointers - Losing my mind
    By drucillica in forum C Programming
    Replies: 5
    Last Post: 11-12-2005, 11:50 PM
  5. 2d Array access by other classes
    By deaths_seraphim in forum C++ Programming
    Replies: 1
    Last Post: 10-02-2001, 08:05 AM