Object-Oriented Programming Using C++ Understanding Arrays, Strings, and Pointers
Learn about memory addresses Learn about arrays Objectives Learn about memory addresses Learn about arrays Store values in an array Access and use array values Avoid common errors with arrays Learn techniques to access part of an array
Objectives (continued) Use parallel arrays Learn how to use strings Discover special string-handling problems Learn about pointers Use a pointer in place of an array name
Understanding Memory Addresses Each location where a piece of data can be stored is identified by a memory address When you declare a variable with a statement such as int myAge; The computer chooses an available memory location Associates the name myAge with the memory address of that location
Understanding Memory Addresses (continued) Address operator Address appears as a hexadecimal number
Understanding Arrays Array: list of items that all have the same type Subscript: number that indicates the position of the particular array element being used Element: single object in an array double moneyCollected[5];
Understanding Arrays (continued) int someNumbers[7]; If you access someNumbers[7], you may get a warning or a garbage value cout<<someNumbers produces the same output as cout<<&someNumbers[0]
Storing Values in an Array int rent[4]; rent[0] = 250; rent[1] = 375; rent[2] = 460; rent[3] = 600; int rent[4] = {250, 375, 460, 600}; int rent[] = {250, 375, 460, 600}; int rent[4] = {250, 375}; int rent[3] = {250, 375, 460, 600}; int rent[4] = {0}; rent[2] and rent[3] are set to 0 Syntax error Sets all array elements to 0
Accessing and Using Array Values
Accessing and Using Array Values (continued) You can also use a variable as a subscript
Accessing and Using Array Values (continued)
Accessing and Using Array Values (continued)
Avoiding Common Array Errors When working with arrays, common errors include: Forgetting that arrays are zero based Accessing locations beyond the array
Forgetting that Arrays are Zero-Based
Accessing Locations Beyond the Array Element is out of bounds
Using Part of an Array Sentinel
Using Part of an Array (continued) Tip: You cannot use a variable to declare an array’s size; you must use a constant
Using Parallel Arrays Parallel arrays are corresponding arrays in which values in the same relative locations are logically related
Using Parallel Arrays (continued)
Using Parallel Arrays (continued)
Using Parallel Arrays (continued) Flag could also be of type bool
Creating Arrays of Structure Objects
Using Strings String: value expressed within double quotes You can type two characters within single quotes when they represent a single character: ‘\n’ “Hello” is a string constant To store a value such as “Hello” -> must create a string variable in one of two ways: Create a string as an array of characters Create a string using the string class defined in the C++ standard library
Strings Created as Arrays of Characters char firstName[] = “Mary”; char firstName[] = {“Mary”}; char firstName[5] = “Mary”; char firstName[5] = {“Mary”}; char firstName[5] = {'M', 'a', 'r', 'y', '\0'}; cout<<firstName; // displays Mary cout<<&firstName[1]; // displays ary Null character. You could also use the constant NULL, defined in iostream
Special String-Handling Problems When Using Character Arrays Some problems occur when strings are declared as character arrays and you: Try to input a string value that includes whitespace Try to assign one string to another using the assignment operator Try to compare strings using the comparison operator Exceed the bounds of an array
Trying to Input a String Value Including Whitespace
Trying to Input a String Value Including Whitespace (continued)
Trying to Assign One String to Another Using the Assignment Operator char clubPresident[10] = {“Eric”}; clubVicePresident[10] = {“Danielle”}; Alternative 1 (does not work as expected): clubPresident = clubVicePresident; Alternative 2 (tedious): clubPresident[0] = clubVicePresident[0]; clubPresident[1] = clubVicePresident[1]; clubPresident[2] = clubVicePresident[2]; Alternative 3 (must include string.h): strcpy(clubPresident, clubVicePresident);
Trying to Compare Strings Using the Comparison Operator Alternative 1 (does not work as expected): if(clubPresident == clubVicePresident) cout<<”They are the same”<<endl; Alternative 2 (tedious): if(clubPresident[0] == clubVicePresident[0] && clubPresident[1] == clubVicePresident[1]. . . Alternative 3 (must include string.h): strcmp(firstName, secName); A return value of 0 indicates they are equal
Exceeding an Array’s Bounds
Pitfall: Exceeding an Array’s Bounds (continued)
An Introduction to the string Class
An Introduction to the string Class (continued)
Pointers: variables that can hold memory addresses Using Pointers Pointers: variables that can hold memory addresses A pointer’s type indicates the type of variable that has an address the pointer can hold For example, int *aPointer; int myValue; aPointer = &myValue; cout<<myValue; //outputs contents of myValue cout<<*aPointer; //outputs contents of myValue cout<<&myValue; //outputs address of myValue cout<<aPointer; //outputs address of myValue
Pointer Variable Declarations and Initialization Can declare pointers to any data type Pointer initialization Initialized to 0, NULL, or address 0 or NULL points to nothing
Pointer Operators & (address operator) Returns memory address of its operand Example int y = 5; int *yPtr; yPtr = &y; // yPtr gets address of y - yPtr “points to” y
* (indirection/dereferencing operator) Pointer Operators * (indirection/dereferencing operator) Returns synonym for object its pointer operand points to *yPtr returns y (because yPtr points to y). dereferenced pointer is 1 value *yptr = 9; // assigns 9 to y * and & are inverses of each other
Using const with Pointers const qualifier Value of variable should not be modified const used when function does not need to change a variable Principle of least privilege Award function enough access to accomplish task, but no more Four ways to pass pointer to function Nonconstant pointer to nonconstant data Highest amount of access Nonconstant pointer to constant data Constant pointer to nonconstant data Constant pointer to constant data Least amount of access
Using const with Pointers const pointers Always point to same memory location Default for array name Must be initialized when declared
Example int main() { int x, y; // ptr is a constant pointer to an integer that can // be modified through ptr, but ptr always points to the // same memory location. int * const ptr = &x; //but if int const *ptr=&x then red line is error //and magenta line is not error *ptr = 7; // allowed: *ptr is not const ptr = &y; // error: ptr is const; cannot assign new address return 0; // indicates successful termination } // end main
Example int main() { int x = 5, y; // ptr is a constant pointer to a constant integer. // ptr always points to the same location; the integer // at that location cannot be modified. const int *const ptr = &x; cout << *ptr << endl; *ptr = 7; // error: *ptr is const; cannot assign new value ptr = &y; // error: ptr is const; cannot assign new address return 0; // indicates successful termination } // end main
Using a Pointer Instead of an Array Name
Using a Pointer Instead of an Array Name (continued)
You Do It: Using an Array
Understanding Memory Addresses cout << "The addresses are " << &firstNum <<" and " << &secondNum << endl;
Summary Each location where a piece of data can be stored is identified by a memory address A list of individual items that all have the same type is called an array A subscript indicates the position of an array element You can initialize an array when you declare it You can access an individual array value just as you would access any variable of the same type
Summary (continued) Common errors when using arrays include: Forgetting that arrays are zero-based Forgetting that the highest legitimate subscript is one less than the array size Use a for loop to access all array elements Parallel arrays contain corresponding elements You can create arrays of structure objects
Summary (continued) A C++ value expressed within double quotes is commonly called a string You can create a string variable As an array of characters With the string class from the C++ standard library Pointers are variables that hold memory addresses To indicate a pointer, begin the variable’s name with an asterisk
Exercises Binary search Only used with sorted arrays Compare middle element with key If equal, match found If key < middle Repeat search on first half of array If key > middle Repeat search on last half
Bubble Sort Using Pass-by-Reference Exercises Bubble Sort Using Pass-by-Reference Implement BubbleSort using pointers Want function swap to access array elements Individual array elements: scalars Passed by value by default Pass by reference using address operator &
Exercises Tokenizing