1 Understanding Arrays and Pointers COSC1567 C++ Programming Lecture 2.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-1 Concordia University Department of Computer Science and Software Engineering COMP345.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1 Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3.
Kernighan/Ritchie: Kelley/Pohl:
Chapter 10.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
1 Arrays In many cases we need a group of nearly identical variables. Example: make one variable for the grade of each student in the class This results.
1 Lecture 20:Arrays and Strings Introduction to Computer Science Spring 2006.
Understanding Arrays and Pointers Object-Oriented Programming Using C++ Second Edition 3.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays.
 2006 Pearson Education, Inc. All rights reserved Pointers.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
Chapter 9: Arrays and Strings
Chapter 5 - Arrays CSC 200 Matt Kayala 2/27/06. Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays.
Chapter 9: Arrays and Strings
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
1 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
Chapter 8 Arrays and Strings
Arrays. Objectives Learn about arrays Explore how to declare and manipulate data into arrays Learn about “array index out of bounds” Become familiar with.
Basic Elements of C++ Chapter 2.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
Chapter 7 Arrays. Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3 Programming with Arrays 7.4 Multidimensional Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays.
CHAPTER 07 Arrays and Vectors (part I). OBJECTIVES 2 In this part you will learn:  To use the array data structure to represent a set of related data.
Chapter 8 Arrays and Strings
EGR 2261 Unit 8 One-dimensional Arrays  Read Malik, pages in Chapter 8.  Homework #8 and Lab #8 due next week.  Quiz next week.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
C/C++ Basics (IV) Array, Pointers and Dynamic Arrays Berlin Chen 2003 Textbook: 1. Walter Savitch, “Absolute C++,” Addison Wesley, 2002 開發代理 2. Walter.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays.
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Slide 1 Chapter 5 Arrays. Slide 2 Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays  Arrays in memory.
Chapter 5 Arrays. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 5-2 Learning Objectives  Introduction to Arrays  Declaring and referencing.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
1 Arrays and Strings Lecture: Design Problem l Consider a program to calculate class average Why?? ?
Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
CSIS 113A Lecture 10 Arrays Glenn Stevenson CSIS 113A MSJC.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Programming Logic and Design Fifth Edition, Comprehensive Chapter 6 Arrays.
For Friday Read No quiz Program 6 due. Program 6 Any questions?
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
Chapter 5 Arrays Copyright © 2016 Pearson, Inc. All rights reserved.
Objectives You should be able to describe: One-Dimensional Arrays
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Computer Programming BCT 1113
8 Pointers.
Object-Oriented Programming Using C++
7 Arrays.
Introduction to C++ Programming
Review of Everything Arrays
CMSC202 Computer Science II for Majors Lecture 03 – Arrays and Functions Dr. Katherine Gibson Based on slides by Chris Marron at UMBC.
7 Arrays.
Chapter 7 Arrays. Chapter 7 Arrays Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3 Programming with Arrays 7.4 Multidimensional.
Presentation transcript:

1 Understanding Arrays and Pointers COSC1567 C++ Programming Lecture 2

2 Objectives Address operator Arrays Store values in an array Access and use array values Array’s size Parallel arrays C-style strings Special string-handling problems Pointers Use a pointer to access an array Multidimensional arrays

3 Using the Address Operator A variable’s memory address is a fixed location; a variable’s address is a constant Although you cannot choose a variable’s actual memory address, you can examine it To do so, you use the address operator (&) The memory address is of not use to you at this point; you use the address operator merely as a curiosity The hexadecimal numbering system uses the values 0 through 9, and the letters a through f to represent the decimal values 0 through 15

4 Using the Address Operator Ex2-1.cpp //console I/O

5 Understanding Arrays A list of individual items that all have the same type is called an array An array holds two or more variables with the same name and type in adjacent memory positions The variables with the same name are distinguished from one another by their subscripts; the subscript is a number that indicates the position of the particular array element being used Anytime you need many related variables, consider using an array

6 Understanding Arrays In C++, you declare an array by using the form type arrayName [size]; where type is any simple type, arrayName is any legal identifier, and size (in the square bracket) represents the number of elements the array contains An element is a single object in an array An array name actually represents a memory address When you declare an array, you tell the compiler to use the array name to indicate the beginning address of a series of elements

7 Understanding Arrays

8 Storing Values in an Array You most often create an array when you want to store a number of related variable elements When you declare an array like int array [4]; you set aside enough memory to hold four integers, but you say nothing about the values stored in those four memory locations The values are unknown—they are whatever was stored in those memory locations before the computer reserved the locations for use by your program Programmers often say that these memory locations are filled with garbage, or useless values

9 Storing Values in an Array Just as you can initialize a single variable when you declare it, you can provide values for an array when you declare it The statement int rent[4] = {250, 375, 460, 600}; provides four values for the array If you declare an array without a size, but provide initialization values, C++ creates an array with the exact size you need If you do not provide enough values to fill an array, C++ fills any unassigned array elements with zeros

10 Program that Uses Single and Array Variables Ex2-2.cpp & Ex2-3.cpp

11 Accessing and Using Array Values The user will be prompted 10 times and allowed to enter a floating point value after each prompt. The 10 values will be stored in price[0] through price[9], respectively The for loop prints arrayInt[0] through arrayInt[4] because x increases from 0 and remains less than 5

12 Using a Constant to Refer to an Array’s Size Often, using a for loop is a convenient way to access all array elements because arrays always have a specific, known size, and for loops execute a specific, known number of times When you want to access all array elements in sequential order, you can use a subscript that you vary from 0 to 1 less than the number of elements of the array

13 Using a Constant to Control Loops A program that declares an array with 12 elements Ex2-5.cpp

14 Accessing Elements in an Array When you want to access a single array element, you use a subscript that indicates the position of the value you want to access When you want to access all of the elements in an array, a for loop usually is convenient A sentinel or dummy is any value that stops a loop’s execution

15 A Program That Averages Up to 30 Test Scores The program declares an array for 30 integer test scores, and single variables that serve as subscripts, a total, and the average Ex2-6.cpp

16 Using Parallel Arrays When you want to access an array element, you use the appropriate subscript If each array element’s position has a logical connection to the array value’s purpose, accessing an array value is a straightforward process Sometimes the numbers you need to access appropriate array values are not small whole numbers

17 A Program That Determines Insurance Premiums Ex2-7.cpp

18 Using Parallel Arrays A better solution is to create two arrays of just four elements each—one to hold the four part numbers, and one to hold the four prices that correspond to those part numbers Such corresponding arrays are called parallel arrays

19 Program That Determines Part Prices Ex2-8.cpp

Initializing Arrays As simple variables can be initialized at declaration: int price = 0;// 0 is initial value Arrays can as well: int children[3] = {2, 12, 1}; –Equivalent to following: int children[3]; children[0] = 2; children[1] = 12; children[2] = 1; 5-20

Auto-Initializing Arrays If fewer values than size supplied: –Fills from beginning –Fills "rest" with zero of array base type If array-size is left out –Declares array with size required based on number of initialization values –Example: int b[] = {5, 12, 11}; Allocates array b to size

Arrays in Functions As arguments to functions –Indexed variables An individual "element" of an array can be function parameter –Entire arrays All array elements can be passed as "one entity" 5-22

Indexed Variables as Arguments Indexed variable handled same as simple variable of array base type Given this function declaration: void myFunction(double par1); And these declarations: int i; double n, a[10]; Can make these function calls: myFunction(i);// i is converted to double myFunction(a[3]);// a[3] is double myFunction(n);// n is double 5-23

Subtlety of Indexing Consider: myFunction(a[i]); –Value of i is determined first It determines which indexed variable is sent –myFunction(a[i*5]); –Perfectly legal, from compiler’s view –Programmer responsible for staying "in-bounds" of array 5-24

Entire Arrays as Arguments Formal parameter can be entire array –Argument then passed in function call is array name –Called "array parameter" Send size of array as well –Typically done as second parameter –Simple int type formal parameter 5-25

Entire Array as Argument Example: Display 5.3 Function with an Array Parameter 5-26 Ex2-9.cpp

Entire Array as Argument Example Given previous example: In some main() function definition, consider this calls: int score[5], numberOfScores = 5; fillup(score, numberOfScores); –1 st argument is entire array –2 nd argument is integer value –Note no brackets in array argument! 5-27

Array as Argument: How? What’s really passed? Think of array as 3 "pieces" –Address of first indexed variable (arrName[0]) –Array base type –Size of array Only 1 st piece is passed! –Just the beginning address of array –Very similar to "pass-by-reference" 5-28

Array Parameters May seem strange –No brackets in array argument –Must send size separately One nice property: –Can use SAME function to fill any size array! –Exemplifies "re-use" properties of functions –Example: int score[5], time[10]; fillUp(score, 5); fillUp(time, 10); 5-29

The const Parameter Modifier Recall: array parameter actually passes address of 1 st element –Similar to pass-by-reference Function can then modify array! –Often desirable, sometimes not! Protect array contents from modification –Use "const" modifier before array parameter Called "constant array parameter" Tells compiler to "not allow" modifications 5-30

Programming with Arrays Plenty of uses –Partially-filled arrays Must be declared some "max size" –Sorting –Searching 5-31

Partially-filled Arrays Difficult to know exact array size needed Must declare to be largest possible size –Must then keep "track" of valid data in array –Additional "tracking" variable needed int numberUsed; Tracks current number of elements in array 5-32

33 Creating Arrays of Class Objects Just as you can create arrays of simple types such as int and double, you can create arrays of class objects To access any individual class object field, you use the object’s individual name, including its subscript, followed by a dot and the field name

34 Creating an Array of Class Objects This program creates an array of four Automobile objects. Ex2-10.cpp

35 Using C-Style Strings In C++, a character variable can hold a single character value, such as ‘A’ or ‘$’ Single character values are always expressed within single quotation marks In C++, if you want to express multiple character values, such as a first name or a book title, you use double quotation marks A C++ value expressed within double quotation marks is commonly called a string

36 Using C-Style Strings You already have used strings with cout statements, as in cout<<“Hello”; Just as a value such as 14 is a numeric constant, a value such as “Hello” is referred to as a string constant In C++ an array of characters and a string are declared in the same way You might create an array of characters if you need to store six one-letter department codes, or five one- letter grades that can be assigned on a test

37 Using Strings The null character is represented by the combination ‘\0’ (backslash and zero), or by using the constant NULL that is available if you use the statement #include at the top of any file you compile

38 Special String Handling Problems String present some special handling problems When you use the cin statement with a string, cin stops adding characters to the string when it encounters white space Often, this means that cin stops when the user presses the Enter key But cin also stops when the user presses the spacebar or the Tab key

39 A Program That Reads a Name

40 Special String Handling Problems Another string handling problem occurs when you attempt to assign one string to another To assign the name of the clubPresident to the same name as the clubVicePresident, you must assign each character value in the clubVicePresident name to the corresponding character location in the clubPresident name A related string-handling problem occurs when you try to compare two strings

41 Special String Handling Problems If you want to determine whether clubPresident and clubVicePresident have the same name, it might seem natural to write a statement such as: if(clubPresident == clubVicePresident) cout<<“They are the same”<<endl; You could write instructions to compare two strings by each character of one string to the corresponding character in the other string, such as in the following: if(clubPresident[0]==clubVicePresident[0] && clubPresident[1]==clubVicePresident[1]...

42 Using the strcmp() Function Ex2-11.cpp

Pointers Pointer variables can be "assigned": int *p1, *p2; p2 = p1; –Assigns one pointer to another –"Make p2 point to where p1 points" Do not confuse with: *p1 = *p2; –Assigns "value pointed to" by p1, to "value pointed to" by p2 43

Pointer Assignments Graphic: Display 10.1 Uses of the Assignment Operator with Pointer Variables 10-44

The new Operator Since pointers can refer to variables… –No "real" need to have a standard identifier Can dynamically allocate variables –Operator new creates variables No identifiers to refer to them Just a pointer! p1 = new int; –Creates new "nameless" variable, and assigns p1 to "point to" it –Can access with *p1 Use just like ordinary variable 45

Basic Pointer Manipulations Example: Display 10.2 Basic Pointer Manipulations (1 of 2) 46

Basic Pointer Manipulations Example: Display 10.2 Basic Pointer Manipulations (2 of 2) 47 Ex2-12.cpp

48

49 Using a Pointer Instead of an Array Name Ex2-13.cpp

50 Using Pointers to Hold Strings Because pointers access computer memory locations, using pointers can be dangerous because you might point to an alter memory locations that you had no intention of altering A dangling reference is when you delete the value pointed to by one of the pointers, and the other pointer is left without a value Ex2-14.cpp

Multidimensional Arrays Arrays with more than one index –char page[30][100]; Two indexes: An "array of arrays" Visualize as: page[0][0], page[0][1], …, page[0][99] page[1][0], page[1][1], …, page[1][99] … page[29][0], page[29][1], …, page[29][99] C++ allows any number of indexes –Typically no more than two 5-51

Multidimensional Array Parameters Similar to one-dimensional array –1 st dimension size not given Provided as second parameter –2 nd dimension size IS given Example: void DisplayPage(const char p[][100], int sizeDimension1) { for (int index1=0; index1<sizeDimension1; index1++) { for (int index2=0; index2 < 100; index2++) cout << p[index1][index2]; cout << endl; } } 5-52 Ex2-15.cpp Ex2-16.cpp

More examples Ex2-17.cpp Ex2-18.cpp Ex2-19.cpp Ex2-20.cpp 53

54 Summary Address operator (&) An array is a list of individual items that are located in adjacent memory positions You can assign values to array elements individually You can access and use an individual array value the same way you would access and use any single variable of the same type A constant is used for the size of an array Parallel arrays Arrays of class objects

55 Summary C-style string Input of a C-style string Pointer variables to hold memory addresses Use a pointer to access an array Multidimensional arrays