C Structs Programming in C++ Fall 2008 Dr. David A. Gaitros
C Structs Structures are aggregate types which means they are built from other types. Format struct { -- declaration list };
C Structs Keyword struct introduces the structure – The name you give the structure must be unique. – Difference structures may have member names with the same name without conflicting with other structures – One structure can contain members of many different types including other structures – A structure cannot contain a member of the same type as itself
C Structs However! – A structure may contain a pointer to itself – This is called a self-referential structure and it is the important basis for forming linked-list structures in C and C++ programming Each structure ends with a left bracket and a semicolon (;) A structure does not reserve space but creates a new type
Introduction to Object Oriented Programming (OOP) C “Struct” Struct Time { int hour; int minute; int second; }; Time Todays_Time; Time Time_Array[10];
C Structs Example with self referential pointer struct personnel { char name[20]; int age; char sex; struct personnel *tPrev; struct personnel *tNext; }; // Now to declare some variables struct Person, *Persons;
C structs Dot (.) operator used in accessing structure members. Used to access members of structures that are not pointers. – The variable structure name followed by a dot (.) and then the member name. – Example Person.age = 53; Person.sex= “M”;
C structs Using the -> notation. Used to access members of a structure (or class) member via a pointer reference. Example code using pointers and structures. // Allocate memory Persons = new struct personnel; Persons->age = 42. Cout age;
C structs A little link list stuff: // Allocate member struct personnel *person1, *person2; Person1 = new struct personnel; Person2 = new struct personnel; Person1->tNext = Person2; Person1->tPrev = NULL; Person2->tPrev = Person1; Person2->tNext = NULL; Person1->age = 40; Person2->age = 50; cout tNext->age; cout << (*Person2).age;