0% found this document useful (0 votes)
72 views

CS205-2020 Spring - Lecture 3 PDF

This document provides an overview of C/C++ programming concepts including compound data types like arrays, strings, structures, unions, enumerations, and pointers. It discusses how to define, initialize, assign values to, and access elements of these data types. Pointers allow programs to indirectly access and manipulate data in memory by storing addresses rather than values. The document also covers memory management and input/output operations using these data types.

Uploaded by

Eason Guan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views

CS205-2020 Spring - Lecture 3 PDF

This document provides an overview of C/C++ programming concepts including compound data types like arrays, strings, structures, unions, enumerations, and pointers. It discusses how to define, initialize, assign values to, and access elements of these data types. Pointers allow programs to indirectly access and manipulate data in memory by storing addresses rather than values. The document also covers memory management and input/output operations using these data types.

Uploaded by

Eason Guan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

C/C++ Programming

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

➢ Cannot convert from a floating-point type to an integer type(narrowing)


➢ Cannot assign int type to char type (Outside the range of a char)
String
Strings
• A string is a series of characters stored in consecutive
bytes of memory
➢ C-style (array) string
➢ string class library
• Store a string in an array of char (C-style)
➢ The last character of every string is the null character
➢ This null character is written \0
➢ The character is with ASCII code 0
➢ It serves to mark the string’s end
Strings
• Using a double quoted string
➢ Called a string constant or string
literal
➢ Include the terminating null character
implicitly

➢ Make sure the array is large enough to


hold all the characters
➢ Note that a string constant (with
double quotes” ”) is not
interchangeable with a character
constant (with single quotes’ ’)
Concatenating String Literals
• C++ enables to concatenate string literals
➢ Any two string constants separated only by whitespace

• Run program example B


➢ Using Strings in an Array
➢ // strings.cpp -- storing strings in an array
• Shortening a string with \0
• Beware of memory overflow (Problem)
Adventures in String Input
• Run program example C
➢ // instr1.cpp -- reading more than one string
➢ The cin technique is to use whitespace—
spaces, tabs, and newlines (\0)—to
delineate a string
➢ The input string might turn out to be
longer than the destination array (buffer)

• A white space causes a problem


Reading String Input a Line at a
Time (solved)
• To solve the problem:
• 1. Line-oriented input with getline()
• See program example D
➢ // instr2.cpp -- reading more than one word with getline()
➢ Two arguments
• 2. Line-oriented input with get()
• Run program example E
➢ Read the single next character, even if it is a newline
➢ // instr3.cpp -- reading more than one word with get() & get()
Mixing String and Numeric Input
• Problem: mixing numeric input with
line-oriented string input
• See a problem in program example F
➢ // numstr.cpp -- following number input with line input
➢ The problem is that when cin reads the
year, it leaves the newline generated by
the Enter key in the input queue. Then
cin.getline() reads the newline as an empty
line and assigns a null string to the address
array
• Solve it: cin.get();
string-class strings
string class
• The ISO/ANSI C++98 Standard expanded the C++ library
• Include the string header file: #include<string>
• Run program example 1
➢ Initialize a string object, in a similar way as a C-style string
➢ Use cin to store keyboard input in a string object
➢ Use cout to display a string object
➢ Use array notation to access individual characters stored in a string object
• Differences
➢ Treat object as a simple variable, not as an array
➢ Allow the program to handle the sizing automatically
C++11 String Initialization
• C++11 enables 4 kinds of initialization
➢ Array-style
➢ String class
• Assign one string object to another
➢ Array assignment

• Use the + and += operators


More string Class Operations
• Three functions for array-style string
➢ strcpy() : copy a string to a character array →=
➢ strcat(): append a string to a character array → +=
➢ strlen(): calculate the length of a character array → ***.size()

• See three operations in program example 2

• 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

➢ Array-style string has fixed size of input


cin.getline(charr, 20); // Array-style string
getline(cin, str); // string class
Other Forms of String Literals
• Beside char, we have more following types
➢ wchar_t
➢ char16_t
➢ char32_t

• Unicode characters called UTF-8


➢ Using u8 prefix to indicate

• C++11 adds a raw string


➢ Delimiter: “( *** )”
➢ Using R prefix to indicate
Structures, Unions and
Enumerations
Introducing Structures
• Why structures?
➢ Almost all previous types are those you can directly use
➢ A structure is a more versatile data form than an array
➢ A structure is a user-definable type
• The keyword struct → make a new type
Using a Structure in a Program
• How to create a structure?
➢ Where to place the structure
declaration? Inside or outside of main
➢ Can a structure use a string class
member? Yes
➢ Assignment: use a comma-separated
list of values enclosed in a pair of
braces
➢ In C++11, the = sign is optional
➢ Empty braces result in the individual
members being set to 0
• See assignment and member
access in program example 4
Other Structure Properties
• What actions you can do for structures?
➢ Pass structures as arguments (multiple) to a function
➢ Have a function use a structure as a return value (multiple)
➢ Combine the definition of a structure form with the creation of
structure variables
➢ Have member functions in addition to member variables
• Run program example 5
➢ Member-wise assignment: use the assignment operator (=) to
assign one structure to another of the same type
More Structure Properties: Array
• Arrays of Structures
➢ Create arrays whose elements are structures
➢ An example
✓ gifts itself is an array, not a structure
✓ gifts[0] is a structure
Unions
• A union is a data format
➢ Can hold different data types but only one
type at a time
➢ Can use two or more formats but never
simultaneously
➢ Save memory
➢ union Keyword → make a new type
program example 5
Enumerations
• The C++ enum facility provides an alternative to
const for creating symbolic constants (#define)
➢ enum spectrum {red, orange, yellow, green, blue, violet};
✓ It makes spectrum the name of a new type
✓ It establishes the members as symbolic constants for the
integer values 0–5
➢ By default, enumerators are assigned integer
values starting with 0 for the first enumerator, 1
for the second enumerator, and so forth
➢ The assigned values must be integers
➢ enum Keyword → make a new type
Enumerations
• What operations can you do for
enumerations?
➢ Assign it using the member
➢ You can set enumerator values
explicitly

➢ Assign other variables using it


➢ Typecast values within the range
➢ Beware of the value ranges for
enumerations
Pointers
Why Needs a Pointer Type?
• Three fundamental properties of declaration
➢ Where the information is stored Identity
➢ What value is kept there - know
Student number
➢ What type of information is stored - know
Address
• How to know where the values are stored? Mobile number
➢ Using address operator & to access the address
➢ Using hexadecimal notation to display the address values
➢ Run program example 6
Pointer Type
• Using ordinary variables
➢ Naturally, the value is treated as a named quantity
➢ The location as the derived quantity
• Using new strategy: pointer type
➢ Inverse way

• Operator *:
➢ Indirect value
➢ The dereferencing operator

• Program example 7
Importance of pointers

•One essential to the C++


programming philosophy of is the
memory management

•Pointers would be the C++


Philosophy
Declaring and Initializing Pointers
• Example: int * birddog;
➢ * birddog is a int type variable
➢ birddog is a pointer type variable
➢ The type for birddog is pointer-to-
int
➢ Put the white space before or
behind the * or no spaces
• int * is a compound type
➢ double *, float *, char *
Pointer Danger
• A confusion for beginners
➢ Creating a pointer in C++ means the computer allocates memory to
hold an address
➢ BUT it does not allocate memory to hold the data
✓ int * ptr; // create a pointer-to-int: NULL
✓ *ptr= 223323; // place a value in never-never land: disaster
Pointers and Numbers
• Similarities and differences between pointer and integer
➢ They are both integers but pointers are not the integer type
➢ Both are numbers you can add and subtract but it doesn’t make
sense to multiply and divide two locations
• Why we need addition and subtraction operations?
• Can’t simply assign an integer to a pointer
• You can do like this:
➢ 0xB8000000 is an address literal (hexadecimal)
➢ int * ptr = (int *) 0xB8000000;
Allocating Memory with new
• What is the problem of the pointer? Remember disaster?
• How to solve it?
➢ The key is the C++ new operator
① Tell new for what data type you want memory
② Let new find a block of the correct size
③ Return the address of the block
④ Assign this address to a pointer
⑤ This is an example: int * ptr_int = new int;
• Now, we have three ways of initialization for a pointer type
• Program example 8
• Operation: sizeof
Freeing Memory with delete
• delete operator enables you to
return memory to the memory
pool
➢ The memory can then be reused
by other parts of the program
➢ Balance the uses of new and delete
➢ Memory leak—memory has been
allocated but no longer being used
• Beware of
➢ Cannot free a block of memory
that you have previously freed
➢ Cannot use delete to free memory
created by ordinary variable
Using new to Create Dynamic
Arrays
• Use new with larger chunks of data, such as arrays, strings,
and structures
➢ Static binding: the array is built in to the program at compile time
➢ Dynamic binding: the array is created during runtime
✓ The size of block can be confirm during runtime

① Don’t use delete to free memory that new didn’t allocate


② Don’t use delete to free the same block of memory twice in succession
③ Use delete [] if you used new [] to allocate an array
④ Use delete (no brackets) if you used new to allocate a single entity
⑤ It’s safe to apply delete to the null pointer (nothing happens)
Using a Dynamic Array
• How do you use the dynamic array?
➢ Identify every element in the block
➢ Access one of these elements
• Program example 9

➢ A pointer points to the first element


➢ double * p3 = new double [3]; // space for 3 doubles
➢ p3 = p3 + 1; // increment the pointer
➢ p3 = p3 - 1; // point back to beginning
Pointers, Arrays, and Pointer
Arithmetic
• Adding one to a pointer variable
increases its value by the number of
bytes of the type to which it points
• Program example 10
➢ You can use pointer names and array
names in the same way
➢ Differences between them
① You can change the value of a pointer,
whereas an array name is a constant
② Applying the sizeof operator to an array
name yields the size of the array, but
applying sizeof to a pointer yields the
size of the pointer
The Address of an Array
What, where and size
• Program example 11
➢ short tell[10];
➢ tell is type pointer-to-short The name of a
➢ &tell is type pointer-to-array of 10 shorts variable can refer
to a value and
➢ short (*pas)[10] = &tell; // try to replace 10 by 20 other information
➢ (*pas) = tell is type pointer-to-short as well
➢ pas=&tell is type pointer-to-array of 10 shorts

➢ 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

➢ The arrow membership


operator (->) of a hyphen and
then a greater-than symbol
• Program example 12 (single)
An Example of Using new and
delete for Functions
• Program example 13
➢ Return the address of the string copy
➢ It’s usually not a good idea to put new and delete in separate
functions
Managing memory for
data
Automatic Storage
• Automatic Storage
➢ Ordinary variables defined inside a function use automatic
storage and are called automatic variables
➢ They expire when the function terminates
➢ Automatic variables typically are stored on a stack
➢ A last-in, first-out, or LIFO, process
Static Storage
• Static Storage
➢ Static storage is storage that exists throughout the execution of
an entire program
➢ Two ways
① Define it externally, outside a function
② Use the keyword static when declaring a variable
static double fee = 56.50;
Dynamic Storage
• Dynamic Storage
➢ The new and delete operators provide a more flexible approach
than automatic and static variables
➢ Refer to as the free store or heap
➢ Lifetime of the data is not tied arbitrarily to the life of the
program or the life of a function
Combinations of Types
• Include arrays, structures, and pointers

• Program example 14: array of structures


➢ const antarctica_years_end * arp[3] = {&s01, &s02, &s03};
➢ const antarctica_years_end ** ppa = arp;
• Distinguish the following (again)
• type_name * variable_name[10] ----- type_name (*variable_name)[10]
Summary
• Compound types
➢ Array
➢ Array-style string
➢ String class
➢ Structure
➢ Pointer: (&), (*),(.),(->)
• Memory management
➢ Automatic Storage
➢ Static Storage
➢ Dynamic Storage
Thanks

[email protected]

You might also like