CS 10061 Introduction to Computer Programming Structures
Arrays (recall) • Recall: – Arrays are containers, they store a number of objects – All the stored objects in an array have the same type – The subscript operator [ ] is used to select one of the objects in the container • The syntax for defining an array is simple since only two things must be specified: – The type of object to be stored – The number of objects that the container will hold
Structures • If we want to have a container that will contain objects of various types we must specify: – What type of objects will be in the container – A name for each object in the container so that each object in the container is uniquely identified • • The name of a component of a container will be used in accessing the component, not subscripting. struct Syntax – A structure definition gives a new type. – Once we have the structure definition we can define variables of the new type.
Structures: Example 1 book 1 and book 2 are each be comprised of 3 strings, 1 int, and 1 double.
Structures Define a New Type • A Structure defines a new type. • The structure definition by itself does not cause any machine language to be generated. • Structure definitions are usually put in a header file and included where the definition is needed. • KEY CONCEPT: Every variable/object of the new type is comprised of all the members specified in the struct definition. • The components of a struct are called members. • The dot operator is used to access a member of a struct.
Structures: Example 2 KEY CONCEPT: Every variable/object of the new type is comprised of all the members specified in the struct definition.