CS205-2020 Spring - Lecture 3 PDF
CS205-2020 Spring - Lecture 3 PDF
Language
CS205 Spring
Feng Zheng
2020.03.05
Content
• Brief Review
• Compound Types
➢ Array
➢ String
➢ string-class string
➢ Structure
➢ Pointer
• Managing memory for data
• Summary
Brief Review
Fundamental types
• Integer Type
➢ Bits and Bytes
➢ Unsigned and signed types
• Char Type
• Floating-point Type
➢ Precision
• Arithmetic Operators
➢ Conversions
Compound Types
Content
• Arrays
• Array-style strings
• string-class strings
• Structures
• Unions
• Enumerations
• Pointers
Array
Arrays
• An array is a data form that can
hold several values, all of one type
• To define:
➢ The type of value to be stored in each
element
➢ The name of the array
➢ The number of elements in the array
must be an integer constant, such as
10 or a const value, MICROS, or a
constant expression Why?
➢ Square brackets []
Arrays
• Some statements for an array
➢ Declaring an array
➢ Assigning values to array elements
➢ Initializing an array
• Run program example A
➢ // arrayone.cpp -- small arrays of integers
➢ Note that if you use the sizeof operator with an array name, you get the
number of bytes in the whole array
➢ First element index is 0
➢ Error: if subscript is equal or greater than the number of elements
Initialization Rules for Arrays
• Several rules about initializing arrays
➢ Can use the initialization form only when defining the array
➢ Cannot use initialization later
➢ Cannot assign one array wholesale to another
➢ Can use subscripts and assign values to the elements of an array
individually
➢ Can partially initialize an array, the compiler sets the remaining
elements to zero
C++11 Array Initialization
• Rules in C++11
➢ Can drop the = sign
• Conclusions
➢ string objects tends to be simpler than using the C string functions
➢ string objects tends to be more safe than that of the C
More on string Class I/O
• See length of string in program example 3
• The difference and problems of array-style string
➢ strlen() reaches a null character
➢ string object is automatically set to zero size
• Operator *:
➢ Indirect value
➢ The dereferencing operator
• Program example 7
Importance of pointers
➢ short* pas[10];
➢ pas is an array of 10 pointers-to-short
•&tell
➢ Applying the address operator yields the address of the whole array
Summarizing Pointer Points
• Pointers
➢ Declaring pointers
➢ Assigning values to pointers (three ways)
➢ Dereferencing pointers: mean referring to the pointed-to value
➢ Distinguishing between a pointer and the pointed-to value
• Array names
➢ Bracket array notation is equivalent to dereferencing a pointer
• Pointer arithmetic
• Dynamic binding and static binding for arrays
Using new to Create Dynamic
Structures
• Dynamic means the memory is
allocated during runtime
➢ Creating the structure
➢ Accessing its members