engineering problem solving with c++ an object based approach chapter 9 pointers and creating data...

26
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

Post on 18-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

Engineering Problem Solving With C++

An Object Based ApproachChapter 9

Pointers and

Creating Data Structures

Page 2: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

Pointer Basics

• A pointer is a variable that holds the memory address of another object

• If a variable p contains the address of another variable q, then p is said to point to q

• If q is a variable at location 0x100 in memory, then p would have the value 0x100 (q’s address)

Page 3: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

Address Of Operator

• The & operator is called the address of operator.

• The operator & in front of any variable produces the address of that variable.

• Example: int x=75;cout << "x is " << x;cout << "\nthe addres of x is " << &x;

75x0x7fff8164

x is 75the address of x is 0x7fff8164

Page 4: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

How to declare a pointer variable

• pointer variables are declared using the indirection operator *, more commonly called the dereferencing operator.

• general form - – type *variable_name, *variable_name;– type* variable_name;

• when declaring more than one pointer variable, the * must precede each variable.

Page 5: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

Example

int *iPtr;double *dPtr;

• the variable iPtr is declared to be of type pointer to int

• the variable dPtr is declared to be of type pointer to double

• neither variable in this example has been initialized

• declaring a pointer creates a variable capable of holding an address

Page 6: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

Example

int *iPtr, i=6;char *s, str = "example";double *dPtr, d=1.25;

iPtr

s

dPtr

6

"example"

1.25

i

str

d

Page 7: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

NULL pointer

• there is a literal value that can be assigned to any pointer

• the literal value is NULL or 0• in this context it is known as the null

address and does not point to anything which can be referenced.

• trying to dereference the null address, results in a fatal error

Page 8: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

Example

int *iPtr=0;

char *s=NULL; //predefined constant in iostream.h

double *dPtr=NULL;

NULL

NULL

NULL

iPtr

s

dPtr

Page 9: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

Assigning values to a pointer

• the assignment operator (=) is defined for pointers

• the right operand of the assignment operator can be any expression that evaluates to the same type as the left

Example:int x, *xp, *ip;xp = &x;ip = xp;

x

xp

ip

Page 10: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

The Base Type

• In the declarationint *p; // the base type of p is

intdouble *q; // the base type of q is double

• Base type determines the size of an object to which the pointer is assumed to be pointing

• The size of p and q are the same ( 4 bytes**), but p points to 4 bytes** and q points to 8 bytes**

**compiler dependent

Page 11: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

Base Type continued

• A pointer’s base type determines how the contents of the memory location pointed to by the pointer will be interpreted

• The declaration:int *p;declares p to be a pointer to int. Whatever p

points to will be interpreted as an intBase type also affects pointer arithmetic

Page 12: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

Assigning/Using Values

• To assign a value using a pointer, use the * to dereference the pointer:

int *iptr, intVal;

iptr = &intVal; // assign iptr to addr intVal

*iptr = 5; // make contents = 5

cout << *iptr << endl; // display contents

cout << iptr << endl; // display address

Page 13: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

Comparing Pointers

• You may compare pointers using relational operators

• Common comparisons are:– check for null pointer (p == NULL)– Note: since NULL evaluates as false, and any other

pointer evaluates as true, checking for a null pointer can be done as (!p)

– check if two pointers are pointing to the same object(p == q)

– Note: (*p == *q) means they are pointing to equivalent, but not necessarily the same data.

Page 14: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

Pointers and Arrays

• The name of an array is the address of the first element (i.e. a pointer to the first element)

• Arrays and pointers may often be used interchangeably

Exampleint num[4] = {1,2,3,4}, *p;p = num;//same as p = &num[0];cout << *p<<endl;p++;cout << *p;

12

Page 15: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

More Pointers and Arrays

• You can also index a pointer using array notation

Example:char myString[] = "This is a string"; char *str;str = myString;for(int i =0; str[i]; i++) //look for null

cout << str[i];

What does this segment print?

This is a string

Page 16: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

Arrays and Pointers

• The name of an array is a pointer to the first element. However, the array name is not a pointer variable. It is a constant pointer that always points to the first element of the array and its value can not be changed.

• Also when an array is declared, space for all elements in the array is allocated, however when a pointer variable is declared only space sufficient to hold an address is allocated

Page 17: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

Common Pointer Problems

• Using uninitialized pointersint *iPtr;*iPtr = 100;iPtr has not been initialized. The value 100 will

be assigned to some memory location. Which one determines the error.

• Failing to reset a pointer after altering it’s value

• Incorrect/unintended syntax

Page 18: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

Dynamic Allocation Using new and delete

• Storage for data is allocated as needed from the free memory area known as the heap (or the freestore).

• Run-time stack– Local variables– Formal parameters– Managed by the compiler

• Heap– Dynamic storage– Managed by storage allocator

Stack

Heap

Global data

Program code

Page 19: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

Dynamic Memory Allocation

• Dynamically allocated memory is determined at runtime

• It allows a program to create as many or as few variables as required, offering greater flexibility

• Dynamic allocation is often used to support data structures such as stacks, queues, linked lists and binary trees.

• Dynamic memory is finite• Dynamically allocated memory may be freed

during execution

Page 20: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

Operator new

• Returns the address of memory allocated on the heap

• If allocation fails, new terminates the program (or returns NULL on older compilers)

Page 21: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

Examples

int *iPtr;

iPtr = new int;// iPtr points to new // integer variable on heap

double *dPtr;dPtr = new double[20]; // dPtr points to the first

// double in an array // of 20 doubles on heap

Page 22: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

int main(){ int *iPtr, i; iPtr = new int; *iPtr = 7; double *dPtr; dPtr = new double[6]; cout << *iPtr << endl; for(i=0; i<6; i++) //SKETCH MEMORY

dPtr[i] = 5;

cout << endl; for(i=0; i<6; i++) cout << dPtr[i] << ' '; return 0; }

OUTPUT7 5 5 5 5 5 5

iPtr

dptr 5 5 5 5 5 5

Practice:

7

Page 23: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

Operator delete

• The delete operator frees memory produced by new

• Using delete to attempt to free any other type of address will produce problems

• While delete uses a pointer variable, it does not destroy the pointer variable, it only frees the storage to which the variable is pointing.

Page 24: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

delete Example

int *ptr;

ptr = new int (100); // can initialize, just like int

cout << *ptr; //see if it worked

delete ptr; //free the memory

value of ptr is now undefined

100

Page 25: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

Example of dynamically allocated arrays

double *dptr;const int size = 10;dptr = new double[size]; //allocate 10 doublesfor(int I=0; I<size; I++) //read values into array

cin >> dptr[I];fun1(dptr, size); // pass array to fun1delete [] dptr; //free all 10 elements

prototype for fun1:

void fun1(double*, int);

Page 26: Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures

Example using delete

int *iPtr, *jPtr; iPtr = new int[3]; for (int i=0; i<3; ++i)

iPtr[i] = i; for (int i=0; i<3; ++i)

cout << iPtr[i] << endl; delete [] iPtr;

jPtr = new int; *jPtr = 5; cout << *jPtr * 7 << endl; delete jPtr;