Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object-Oriented Programming Using C++

Similar presentations


Presentation on theme: "Object-Oriented Programming Using C++"— Presentation transcript:

1 Object-Oriented Programming Using C++
Understanding Arrays, Strings, and Pointers

2 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

3 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

4 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

5 Understanding Memory Addresses (continued)
Address operator Address appears as a hexadecimal number

6 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];

7 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]

8 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

9 Accessing and Using Array Values

10 Accessing and Using Array Values (continued)
You can also use a variable as a subscript

11 Accessing and Using Array Values (continued)

12 Accessing and Using Array Values (continued)

13 Avoiding Common Array Errors
When working with arrays, common errors include: Forgetting that arrays are zero based Accessing locations beyond the array

14 Forgetting that Arrays are Zero-Based

15 Accessing Locations Beyond the Array
Element is out of bounds

16 Using Part of an Array Sentinel

17 Using Part of an Array (continued)
Tip: You cannot use a variable to declare an array’s size; you must use a constant

18 Using Parallel Arrays Parallel arrays are corresponding arrays in which values in the same relative locations are logically related

19 Using Parallel Arrays (continued)

20 Using Parallel Arrays (continued)

21 Using Parallel Arrays (continued)
Flag could also be of type bool

22 Creating Arrays of Structure Objects

23 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

24 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

25 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

26 Trying to Input a String Value Including Whitespace

27 Trying to Input a String Value Including Whitespace (continued)

28 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);

29 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

30

31 Exceeding an Array’s Bounds

32 Pitfall: Exceeding an Array’s Bounds (continued)

33 An Introduction to the string Class

34 An Introduction to the string Class (continued)

35 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

36 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

37 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

38 * (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

39 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

40 Using const with Pointers
const pointers Always point to same memory location Default for array name Must be initialized when declared

41 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

42 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

43 Using a Pointer Instead of an Array Name

44 Using a Pointer Instead of an Array Name (continued)

45 You Do It: Using an Array

46 Understanding Memory Addresses
cout << "The addresses are " << &firstNum <<" and " << &secondNum << endl;

47 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

48 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

49 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

50 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

51 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 &

52 Exercises Tokenizing


Download ppt "Object-Oriented Programming Using C++"

Similar presentations


Ads by Google