Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

1 Lecture 2 Arrays, Pointers, and Structures

2 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

3 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)

4 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.

5 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

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

7 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

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

9 How to do Vector’s resize

10

11

12 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.

13 Primitive Array of constant Multidimensional Array

14 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

15 Strings

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

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

18 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

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

20 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

21 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.

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

23 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.

24 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.

25 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

26 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.

27 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

28 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; 12345 “Nina “Weiss” st Illustration of a shallow copy

29 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.

30 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?

31 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?

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

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


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

Similar presentations


Ads by Google