Professional Documents
Culture Documents
Pointers
9.1
Getting the Address of a Variable
9.2
Pointer Variables
Pointer Variables
Pointer variable : Often just called a pointer, it's a variable that holds an address
Because a pointer variable holds the address of another piece of data, it "points" to the data
showValues(numbers, SIZE);
Pointer Variables
Pointer variables are yet another way using a memory address to work with a piece of data. Pointers are more "low-level" than arrays and reference variables. This means you are responsible for finding the address you want to store in the pointer and correctly using it.
Pointer Variables
Definition:
int *intptr;
Read as: intptr can hold the address of an int Spacing in definition does not matter:
int * intptr; int* intptr; // same as above // same as above
Pointer Variables
Assigning an address to a pointer variable:
int *intptr; intptr = #
Memory layout:
num
25 address of num: 0x4a00
intptr
0x4a00
9-16
Copyright 2012 Pearson Education, Inc.
9.3
The Relationship Between Arrays and Pointers
11
9-20
Copyright 2012 Pearson Education, Inc.
Pointers in Expressions
Given:
int vals[]={4,7,11}, *valptr; valptr = vals;
Array Access
Array elements can be accessed in many ways:
Array access method array name and [] pointer to array and [] Example vals[2] = 17; valptr[2] = 17;
*(vals + 2) = 17;
*(valptr + 2) = 17;
Array Access
Conversion: vals[i] is equivalent to *(vals + i)
No bounds checking performed on array access, whether using array name or a pointer
9.4
Pointer Arithmetic
Pointer Arithmetic
Operations on pointer variables:
Operation Example
int vals[]={4,7,11}; int *valptr = vals; valptr++; // points at 7 valptr--; // now points at 4
++, --
9.5
Initializing Pointers
Initializing Pointers
Can initialize at definition time:
int num, *numptr = # int val[3], *valptr = val;
9.6
Comparing Pointers
Comparing Pointers
Relational operators (<, >=, etc.) can be used to compare addresses in pointers Comparing addresses in pointers is not the same as comparing contents pointed at by pointers:
if (ptr1 == ptr2) // // if (*ptr1 == *ptr2) // // compares addresses compares contents
9-31
Copyright 2012 Pearson Education, Inc.
9.7
Pointers as Function Parameters
A pointer can be a parameter Works like reference variable to allow change to argument from within function Requires:
1)
2) 3)
Example
void swap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; } int num1 = 2, num2 = -3; swap(&num1, &num2);
(Program Continues)
Copyright 2012 Pearson Education, Inc.
Pointers to Constants
If we want to store the address of a constant in a pointer, then we need to store it in a pointer-to-const.
Pointers to Constants
Example: Suppose we have the following definitions:
const int SIZE = 6; const double payRates[SIZE] = { 18.55, 17.45, 12.85, 14.97, 10.35, 18.89 };
Pointers to Constants
Suppose we wish to pass the payRates array to a function? Here's an example of how we can do it.
void displayPayRates(const double *rates, int size) { for (int count = 0; count < size; count++) { cout << "Pay rate for employee " << (count + 1) << " is $" << *(rates + count) << endl; } }
The parameter, rates, is a pointer to const double.
Copyright 2012 Pearson Education, Inc.
Constant Pointers
A constant pointer is a pointer that is initialized with an address, and cannot point to anything else. Example int value = 22; int * const ptr = &value;
Copyright 2012 Pearson Education, Inc.
Constant Pointers
9.8
Dynamic Memory Allocation
Notice that in line 49 the value 0 is assigned to the sales pointer. It is a good practice to store 0 in a pointer variable after using delete on it. First, it prevents code from inadvertently using the pointer to access the area of memory that was freed. Second, it prevents errors from occurring if delete is accidentally called on the pointer again. The delete operator is designed to have no effect when used on a null pointer.
Copyright 2012 Pearson Education, Inc.
9.9
Returning Pointers from Functions
The function must not return a pointer to a local variable in the function. A function should only return a pointer:
to data that was passed to the function as an argument, or to dynamically allocated memory
Chapter 10:
Characters, CStrings, and More About the string Class
10.1
Character Testing
Character Testing
require cctype header file
FUNCTION MEANING
isalpha
isalnum isdigit islower isprint ispunct isupper isspace
10.2
Character Case Conversion
Functions:
toupper: if char argument is lowercase letter, return uppercase equivalent; otherwise, return input unchanged char ch1 = 'H'; char ch2 = 'e'; char ch3 = '!'; cout << toupper(ch1); // displays 'H' cout << toupper(ch2); // displays 'E' cout << toupper(ch3); // displays '!'
Copyright 2012 Pearson Education, Inc.
10.3
C-Strings
C-Strings
C-string: sequence of characters stored in adjacent memory locations and terminated by NULL character String literal (string constant): sequence of characters enclosed in double quotes " " : "Hi there!"
H i t h e r e ! \0
C-Strings
Array of chars can be used to define storage for string: const int SIZE = 20; char city[SIZE];
Leave room for NULL at end Can enter a value using cin or >>
Input is whitespace-terminated No check to see if enough space
For input containing whitespace, and to control amount of input, use cin.getline()
Copyright 2012 Pearson Education, Inc.
10.4
Library Functions for Working with C-Strings
Note: strcat and strcpy perform no bounds checking to determine if there is enough space in receiving character array to hold the string it is being assigned.
Copyright 2012 Pearson Education, Inc.
10.5
C-String/Numeric Conversion Functions
itoa does no bounds checking make sure there is enough space to store the result
Copyright 2012 Pearson Education, Inc.
10.6
Writing Your Own C-String Handling Functions
10.6
Writing Your Own C-String Handling Functions
10.7
More About the C++ string Class
string Comparison
Can use relational operators directly to compare string objects:
string str1 = "George", str2 = "Georgia"; if (str1 < str2) cout << str1 << " is less than " << str2;
Meaning
defines an empty string object defines a string and initializes it defines a string and initializes it defines a string and initializes it with first 3 characters of myname defines a string and initializes it with 2 characters from myname starting at position 3 defines string and initializes it to 5 'A's
string Operators
OPERATOR >> << = += + [] >, >=, <, <=, ==, != MEANING extracts characters from stream up to whitespace, insert into string inserts string into stream assigns string on right to string object on left appends string on right to end of contents on left concatenates two strings references character in string using array notation relational operators for string comparison. Return true or false
string Operators
string word1, phrase; string word2 = " Dog"; cin >> word1; // user enters "Hot Tamale" // word1 has "Hot" phrase = word1 + word2; // phrase has // "Hot Dog" phrase += " on a bun"; for (int i = 0; i < 16; i++) cout << phrase[i]; // displays // "Hot Dog on a bun"
Chapter 11:
Structured Data
11.1
Abstract Data Types
User of an abstract data type does not need to know the implementation of the data type, e.g., how the data is stored ADTs are created by programmers
Data Type defines the values that can be stored in a variable and the operations that can be performed on it
11.2
Combining Data into Structures
Defining Variables
struct declaration does not allocate memory or create variables To define variables, use structure tag as type name:
Student bill;
bill studentID name
yearInSchool gpa
11.3
Accessing Structure Members
Member variables can be used in any manner appropriate for their data type
11-107
Copyright 2012 Pearson Education, Inc.
11.4
Initializing a Structure
Initializing a Structure
struct variable can be initialized when defined:
Student s = {11465, "Joan", 2, 3.75};
Cannot initialize in the structure declaration, since this does not allocate memory
11.5
Arrays of Structures
Arrays of Structures
Structures can be defined in arrays Can be used in place of parallel arrays
const int NUM_STUDENTS = 20; Student stuList[NUM_STUDENTS];
Individual structures accessible using subscript notation Fields within structures accessible using dot notation:
cout << stuList[5].studentID;
11.6
Nested Structures
Nested Structures
A structure can contain another structure as a member:
struct PersonInfo { string name, address, city; }; struct Student { int studentID; PersonInfo pData; short yearInSchool; double gpa; };
Copyright 2012 Pearson Education, Inc.
11.7
Structures as Function Arguments
Can use reference parameter if function needs to modify contents of structure variable
11.8
Returning a Structure from a Function
11.9
Pointers to Structures
Pointers to Structures
A structure variable has an address Pointers to structures are variables that can hold the address of a structure:
Student *stuPtr;
Can use structure pointer operator to eliminate () and use clearer notation:
cout << stuPtr->studentID;
11-138
Copyright 2012 Pearson Education, Inc.
11.11
Unions
Unions
Similar to a struct, but
all members share a single memory location, and only one member of the union can be used at a time
Declared using union, otherwise the same as struct Variables defined as for struct variables
Anonymous Union
A union without a union tag:
union { ... };
11.12
Enumerated Data Types
The identifiers MONDAY, TUESDAY, WEDNESDAY, THURSDAY, and FRIDAY, which are listed inside the braces, are enumerators. They represent the values that belong to the Day data type.
Copyright 2012 Pearson Education, Inc.
workDay = static_cast<Day>(3);
This code declares the Car data type and defines a variable named sportsCar.
Chapter 12:
Advanced File Operations
12.1
File Operations
File Operations
File: a set of data stored on a computer, often on a disk drive Programs can read from, write to files Used in many applications:
Word processing Databases Spreadsheets Compilers
Using Files
1. Requires fstream header file
use ifstream data type for input files use ofstream data type for output files use fstream data type for both input, output files
2. Can use >>, << to read from, write to a file 3. Can use eof member function to test for end of input file
fstream Object
fstream object can be used for either input or output Must specify mode on the open statement Sample modes:
ios::in input ios::out output
ofstream:
open for output only file cannot be read from file created if no file exists file contents erased if file exists
Can also check fail member function to detect file open error:
if (gradeList.fail()) ...
Copyright 2012 Pearson Education, Inc.
12.2
File Output Formatting
12.3
Passing File Stream Objects to Functions
12.4
More Detailed Error Testing
fail()
bad() good() clear()
12.5
Member Functions for Reading and Writing Files
12.6
Working with Multiple Files
12.7
Binary Files
Binary Files
Binary file contains unformatted, non-ASCII data
Indicate by using binary flag on open:
inFile.open("nums.dat", ios::in | ios::binary);
12-202
Copyright 2012 Pearson Education, Inc.
Binary Files
Use read and write instead of <<, >>
char ch; // read in a letter from file inFile.read(&ch, sizeof(ch));
address of where to put the data being read in. The read function expects to read chars
Binary Files
To read, write non-character data, must use a typecast operator to treat the address of the data as a character address
int num; // read in a binary number from a file inFile.read(reinterpret_cast<char *>&num, sizeof(num)); treat the address of num as
the address of a char
12.8
Creating Records with Structures
12-206
Copyright 2012 Pearson Education, Inc.
12.9
Random-Access Files
Random-Access Files
Sequential access: start at beginning of file and go through data in file, in order, to end
to access 100th entry in file, go through 99 preceding entries first
12-210
Copyright 2012 Pearson Education, Inc.
Examples:
inData.seekg(25L, ios::beg); // set read position at 26th byte // from beginning of file outData.seekp(-10L, ios::cur); // set write position 10 bytes // before current position
12-211
Copyright 2012 Pearson Education, Inc.
12-212
Copyright 2012 Pearson Education, Inc.
12.10
Opening a File for Both Input and Output