Chapter 1 Arrays, Pointers, and Structures - PowerPoint PPT Presentation

1 / 28
About This Presentation
Title:

Chapter 1 Arrays, Pointers, and Structures

Description:

Dangling/stale pointers. Example 1. string *s = new string('hello' ... delete t; // s becomes invalid //= stale/dangling pointer ... – PowerPoint PPT presentation

Number of Views:78
Avg rating:3.0/5.0
Slides: 29
Provided by: Ken695
Category:

less

Transcript and Presenter's Notes

Title: Chapter 1 Arrays, Pointers, and Structures


1
Chapter 1Arrays, 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
1.1 What are Arrays, Pointers, and Structures?
  • Aggregate collection of objects stored in one
    unit
  • Arrays indexed collections of identical-type
    objects. (aggregate)
  • Pointers objects are used to access other
    objects.
  • 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 , lt
  • 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 ltvectorgt
  • Declaration vectorlttypegt identifiers(size)
  • Example vectorltintgt a(3)
  • Vector can be indexed as an array, using

7
Vectors
  • Vector member functions
  • vectorltintgt 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 Vectors resize
  • Example
  • vectorltintgt arr(10)
  • arr.resize(12)

9
Parameter-Passing Mechanisms
  • Call by value
  • int findMax(vectorltintgt 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.

10
Parameter-Passing Mechanisms
  • Call by reference
  • int findMax(vectorltintgt a)
  • It avoids a copy, but allows changes to the
    parameter
  • Call by constant reference
  • int findMax(const vectorltintgt a)
  • It avoids copy and guarantees that actual
    parameter will not be change.

11
Strings
  • includeltstringgt
  • string sHello World!
  • Int sizes.length()
  • coutltlt s4 ltltendl // resulto
  • coutltlt s ltltendl
  • s.c_str() returns a \0 terminated primitive
    character array.
  • , concatenation

12
Pointers
  • Declare a pointer
  • int ptr
  • referencing operator that returns the address
    of the object.
  • dereferencing operator which can access data
    through a pointer

13
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 a5

14
Pointers
  • iPtr vs. iPtr vs. iPtr
  • iPtr 5 vs. iPtr b vs. iPtr b
  • ptr1 ptr2 vs. ptr1 ptr2
  • ptr1 ptr2 vs. ptr1 ptr2

15
Pointers Cont
  • Precedence rules applied on pointer arithmetic
  • int a 10
  • int ptr a
  • ptr 1
  • // returns a11
  • ptr
  • //advances ptr to the next memory slot

ptr
a
10
a
11
ptr
11
ptr
16
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.

17
Figure1.10
  • include ltiostreamgt
  • include ltstringgt
  • using namespace std
  • int main()
  • string strPtr
  • strPtr new string(hello)
  • coutltlt The string is ltlt strPtrltltendl
  • delete strPtr
  • return 0

18
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
    //gtstale/dangling pointer
  • delete s // another problemgtdouble
    //deletion
  • Example 2
  • string function1()
  • string s hello return s
  • cout ltltfunction1()ltltendl
  • // run time error because s no longer exists
    since function returned.

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

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

22
Structures
  • Struct Student
  • string firstName
  • string lastName
  • Student a, sPtr // declaring Student
  • a.firstName Mary//accessing member data
  • sPtr a
  • (sPtr).lastName Smith
  • //sPtr-gtlastName Smith // same as above

23
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
  • struct Teacher
  • string firstName
  • string lastName
  • int employeeNum
  • Teacher s, t
  • st

Nina
12345
12345
s
t
Weiss
Illustration of a shallow copy
24
Common mistakes
  • Void swapWrong(int a, int b)
  • int tmpa
  • ab
  • btmp
  • What is wrong here?
  • Answer swapWrong doesnt work because of call by
    value restrictions.

25
Common mistakes
  • If ptr is uninitialized, ptrx will cause
    problems. Why?
  • In declaration ptrx initializes ptr to point
    at x. In an assignment statement this is wrong.
    Why?
  • When is ptr1ptr2 true?

26
Class exercise
  • int a, b
  • int ptr //a pointer
  • int ptrPtr //a pointer to pointer
  • ptra
  • ptrPtrptr
  • 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?

27
  • d. is the following statement legal?
  • ptrPtrptr

28
Summary
  • Vectors vs. arrays
  • First class objects vs. second class objects
  • Ways to pass data to functions
  • Pointers
  • Dynamic memory allocation deallocation
  • and . Operators -gt
Write a Comment
User Comments (0)
About PowerShow.com