Lecture Notes for Introduction to Computer Science II
29 May 2001 - Structures
- collect related data into groups
- inconvenient to manipulate
- easy to forget some parts
- keeping data from more than one group from mingling
- structs group related data
- syntax -
struct
struct-name
{ type name
; . . . };
- the data in a struct are called fields
- the field type can be anything
- all field names within the same struct must be different
- a struct may have any number of fields, including 0
- declaring structs
- a struct is like any other datatype
- variable declarations - struct-name var-name1
,
var-name2, . . .,
var-namen;
- function declarations - struct-name1
f(
struct-name2 param-name) { . . . }
- accessing fields
- use the dot operator
.
to access a struct's fields
- the fields are just like regular variables
- a field must be accessed through a struct
- using structs
- stucts may be passed around like any other variable
- you can, eventually, treat structs like any other variable
- the struct definition must appear in the same file as field accesses
This page last modified on 29 May 2001.