Lecture 2 Arrays, Pointers, and Structures. Objective In this chapter, we will discuss several concepts: Arrays (first-class arrays, using vector) Strings.

Slides:



Advertisements
Similar presentations
Introduction to Linked Lists In your previous programming course, you saw how data is organized and processed sequentially using an array. You probably.
Advertisements

Chapter 9 Pointers and Dynamic Arrays. Overview 9.1 Pointers 9.2 Dynamic Arrays.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
Chapter 9. 2 Objectives You should be able to describe: Addresses and Pointers Array Names as Pointers Pointer Arithmetic Passing Addresses Common Programming.
Pointers “Absolute C++” Section 10.1
Starting out with C++1 Chapter 9 – Pointers Getting the address of a Variable Why do we have pointers? Indirection – difference between –Will you go out.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
1 ES 314 Advanced Programming Lec 3 Sept 8 Goals: complete discussion of pointers discuss 1-d array examples Selection sorting Insertion sorting 2-d arrays.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic.
Programming Pointers. COMP104 Lecture 32 / Slide 2 Pointers l Pointers are objects whose values are the locations of other objects l Pointers are memory.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Dr. Yingwu Zhu STL Vector and Iterators. STL (Standard Template Library) 6:14:43 AM 2 A library of class and function templates Components: 1. Containers:
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Pointers CS362. Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes.
Microsoft Visual C++.NET Chapter 61 Memory Management.
Chapter 9 Pointers Fall 2005 Csc 125 Introduction to C++
Pointers Chapter 9. Getting The Address Of A Variable Each variable in program is stored at a unique address Use address operator & to get address of.
February 11, 2005 More Pointers Dynamic Memory Allocation.
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 26: Exam 2 Preview.
1 Pointers Arrays have a disadvantage: Their size must be known at compile time. We would like the capability to allocate an array-like object of any needed.
Chapter 1 Arrays, Pointers, and Structures Saurav Karmakar Spring 2007.
Pointers, Variables, and Memory. Variables and Pointers When you declare a variable, memory is allocated to store a value. A pointer can be used to hold.
Recap Visual Perception and Data Visualization Types of Information Display Examples of Diagrams used for Data Display Planning Requirement for Data Visualization.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 13: Pointers You are not responsible for virtual functions (starting on.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
CPSC 252 Dynamic Memory Allocation Page 1 Dynamic memory allocation Our first IntVector class has some serious limitations the capacity is fixed at MAX_SIZE.
Dynamic memory allocation and Pointers Lecture 4.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
CS102 Introduction to Computer Programming Chapter 9 Pointers.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Review 1 List Data Structure List operations List Implementation Array Linked List.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved This Weeks Topics: Pointers (continued)  Modify C-String through a function call 
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.
Lecture 10: 2/17/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
CPS120: Introduction to Computer Science Lecture 16 Data Structures, OOP & Advanced Strings.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
1  Lecture 12 – Pointer FTMK, UTeM – Sem /2014.
CS162 - Topic #6 Lecture: Pointers and Dynamic Memory –Review –Dynamically allocating structures –Combining the notion of classes and pointers –Destructors.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Windows Programming Lecture 03. Pointers and Arrays.
Recap Resizing the Vector Push_back function Parameters passing Mechanism Primitive Arrays of Constants Multidimensional Arrays The Standard Library string.
Topic 5 Addresses, Pointers and Arrays. 2 Objectives (Textbook Chapter 14) You should be able to describe: Addresses and Pointers Pointer Operators Pointer.
Pointers and Dynamic Arrays
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Motivation and Overview
Review Bernard Chen Spring 2006.
Java Review: Reference Types
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 15 Pointers, Dynamic Data, and Reference Types
Presentation transcript:

Lecture 2 Arrays, Pointers, and Structures

Objective In this chapter, we will discuss several concepts: Arrays (first-class arrays, using vector) Strings (using string) Pointers Dynamic allocation Reference variables and parameter passing mechanisms Structures

What are Arrays, Pointers, and Structures Pointer: A pointer is an object that can be used to access another object. A pointer provides indirect access rather than direct access to an object. People use pointers in real- life situations all the time. Professor says: Do Problem 1.1 in the textbook looking up a topic in the index of a book. A street address is a pointer. It tells you where someone resides. A uniform resource locator (URL),such as http : / /www. cnn.com, Aggregate: collection of objects stored in one unit Arrays: indexed collections of identical-type objects. (aggregate) Structures: collections of objects that need not be of the same type. (aggregate)

1.2 Arrays and Strings Arrays: indexed collections of identical-type objects. Array always start on 0 Arrays can be used in two different ways: primitive arrays and vectors. Vectors vs. Primitive Arrays – Vector has variable size and supports many manipulation functions – Primitive Array has fixed size, and support only a few of manipulation functions.

First class vs. Second Class objects First class object (vectors, string class) : can be manipulate in all the usual ways. – A vector knows how large it is – 2 string objects can be compared with ==, < – Both vector and string can be copied with = second class object (arrays) : can be manipulate in only certain restricted ways. – A built-in array cannot be copied with =, – A built-in array doe not remember how many items it can store, – And its indexing operator does not check that the index is valid – The built-in string is simply an array of characters, and thus has the liabilities of array; plus a few more. For instance, == does not correctly compare 2 built-in strings

Vectors #include Declaration: vector identifiers(size); Example: vector a(3); Vector can be indexed as an array, using [ ]

Vectors Vector member functions: vector v(10); v.at() // equal to v[ ] v.size() // return the number of elements in v v.front() // return the first element in v v.back() // return the last element in v v.clear() // delete all the element in v v.empty() // return 1 if v is empty; else return 0 v.resize( val ) // change size of v to val v.pop_back() // remove the last element in v v.push_back( val ) // appends val to the end of v v.capacity() // return the number of element that vector can hold before it will need to allocate more space

How to do Vector’s resize Example: vector arr(10); arr.resize(12);

How to do Vector’s resize

Parameter-Passing Mechanisms Call by value int findMax(vector a); – It is the value of the variable that is passed, rather than the variable itself (that is, the address of the variable). – It is safe, but expensive due to argument copying. Call by reference int findMax(vector &a); – It avoids a copy, but allows changes to the parameter Call by constant reference int findMax(const vector &a); – It avoids copy and guarantees that actual parameter will not be change.

Primitive Array of constant Multidimensional Array

Strings #include string s=“Hello World!”; Int size=s.length(); cout<< s[4] <<endl; // result:“o” cout<< s <<endl; s.c_str() returns a ‘\0’ terminated primitive character array. +, +=: concatenation

Strings

Pointers Declare a pointer int *ptr; & : referencing operator that returns the address of the object. * : dereferencing operator which can access data through a pointer

Pointers Declare a pointer int *ptr; & : referencing operator that returns the address of the object. * : dereferencing operator which can access data through a pointer

Pointers … int a = 3; int * iPtr; //declares iPtr points to an object of type int iPtr = &a; // points iPtr to the memory address of variable a. *iPtr = 5; // what is the value of a ? Answer: a=5

Pointers … *iPtr vs. &iPtr vs. iPtr *iPtr = 5 vs. *iPtr = b vs. iPtr = &b ptr1 == ptr2 vs. *ptr1 == *ptr2 ptr1 = ptr2 vs. *ptr1 = *ptr2

Pointers Cont… Precedence rules applied on pointer arithmetic int a = 10; int *ptr = &a; *ptr += 1; // += returns a=11 *ptr++; //advances ptr to the next memory slot 10 ptr 11 ptr 11 a a

1.4 Dynamic memory management Objects can be created dynamically by calling new new operator allocates memory and returns a pointer to the newly created object. When an object that is allocated by new is no longer referenced, applied delete operator on this object, through its pointer, to avoid “memory leakage” If delete is not used, the memory that the object consumes is lost until the program terminates.

Figure1.10 #include using namespace std; int main(){ string *strPtr; strPtr = new string(“hello”); cout<< “The string is: “<< *strPtr<<endl; … delete strPtr; return 0; }

Dangling/stale pointers Example 1 string *s = new string(“hello”); string *t = s; // t & s point to the same block delete t; // s becomes invalid //=>stale/dangling pointer delete s; // another problem=>double //deletion Example 2 string *function1() { string s = “hello”; return &s;} cout <<*function1()<<endl; // run time error because s no longer exists since function returned.

1.5 Reference variables A reference type is an alias for another object and may be viewed as a pointer constant that is always dereferenced implicitly. int long_name = 0; int &cnt = long_name; //cnt is an alias cnt += 3; // long_name = 3 Must be initialized when they are declared.

Differences between ref. and pointers void swapRef(int &a, int &b){ int tmp = a; a = b; b = tmp; } int main(){ int x = 3; int y = 5; swapVal(x, y); //call by value swapPtr(&x, &y); // call by pointer swapRef(x, y); //call by reference return 0; } void swapVal(int a, int b){ int tmp = a; a = b; b = tmp; } void swapPtr(int *a, int *b){ int tmp = *a; *a = *b; b* = tmp; } References are implicitly dereferenced

Structures Stores a collection of objects that need not be of the same type. Each object in the structure is a member and is accessed by applying the dot (.) member operator, not index as in array. In C, structures are used quite often. But in C++, they are replaced by classes at most cases.

Structures Struct Student{ string firstName; string lastName; … }; Student a, *sPtr; // declaring Student a.firstName = “Mary”;//accessing member data sPtr = &a; (*sPtr).lastName = “Smith”; //sPtr->lastName = “Smith”; // same as above

Copying objects Shallow copy: a copy of pointers rather than data being pointed at Deep copy: a copy of data being pointed at rather than the pointers. Example s truct Teacher{ string *firstName; string *lastName; int employeeNum; }; Teacher s, t; … s=t; “Nina “Weiss” st Illustration of a shallow copy

Common mistakes: Void swapWrong(int a, int b) { int tmp=a; a=b; b=tmp } What is wrong here? Answer: swapWrong doesn’t work because of call by value restrictions.

Common mistakes: If ptr is uninitialized, *ptr=x will cause problems. Why? In declaration *ptr=&x initializes ptr to point at x. In an assignment statement this is wrong. Why? When is ptr1==ptr2 true?

Class exercise int a, b; int *ptr; //a pointer int **ptrPtr //a pointer to pointer ptr=&a; ptrPtr=&ptr; a. Is this code legal? b. What are the values of *ptr and **ptrPtr c. How can you alter ptrPtr, so that it points at a pointer to b without directly touching ptr?

d. is the following statement legal? ptrPtr=ptr;

Summary Vectors vs. arrays First class objects vs. second class objects Ways to pass data to functions Pointers Dynamic memory allocation & deallocation “*” and “.” Operators: “->”