lecture 2 arrays, pointers, and structures. objective in this chapter, we will discuss several...

33
Lecture 2 Arrays, Pointers, and Structures

Upload: garey-mathews

Post on 28-Dec-2015

220 views

Category:

Documents


1 download

TRANSCRIPT

Lecture 2Arrays, 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 <vector>• Declaration: vector<type> identifiers(size); Example: vector<int> a(3);

• Vector can be indexed as an array, using [ ]

VectorsVector member functions:

vector<int> 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<int> arr(10); arr.resize(12);

How to do Vector’s resize

Parameter-Passing Mechanisms• Call by value

int findMax(vector<int> 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 referenceint findMax(vector<int> &a);– It avoids a copy, but allows changes to the parameter

• Call by constant reference int findMax(const vector<int> &a); – It avoids copy and guarantees that actual parameter will

not be change.

Primitive Array of constant

Multidimensional Array

Strings

• #include<string> 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 intiPtr = &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

10ptr

11ptr

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 <iostream>#include <string>using namespace std;int main(){string *strPtr;strPtr = new string(“hello”);cout<< “The string is: “<< *strPtr<<endl;

… delete strPtr; return 0;}

Dangling/stale pointersExample 1string *s = new string(“hello”);string *t = s; // t & s point to the same blockdelete t; // s becomes invalid

//=>stale/dangling pointerdelete s; // another problem=>double

//deletionExample 2string *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 valueswapPtr(&x, &y); // call by pointerswapRef(x, y); //call by referencereturn 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 Studenta.firstName = “Mary”;//accessing member datasPtr = &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.

Examplestruct Teacher{string *firstName;string *lastName;int employeeNum;};Teacher s, t;…s=t;

12345 12345

“Nina

“Weiss”

s t

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 pointerint **ptrPtr //a pointer to pointerptr=&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: “->”