Docsity

Pointers Linked Lists - Data Algorithms - Lecture Slides, Slides of Algorithms and Programming

Partial preview of the text

Download Pointers Linked Lists - Data Algorithms - Lecture Slides and more Slides Algorithms and Programming in PDF only on Docsity!

Pointers & Linked Lists

Run-Time Arrays — Intro. to Pointers

For declarations like double doubleVar; char charVar = 'A'; int intVar = 1234;

the compiler constructs the object being declared, which means that it:

**1. Allocates memory needed for that type of object

  1. Associates the object's name with that memory
  2. Initializes that memory**

Read (§8.4 & §8.5)

A

#include using namespace std;

int main() { int i = 11, j = 22; double d = 3.3, e = 4.4; // pointer variables that: // store addresses of ints

Output produced: &i = 0x7fffb7f &j = 0x7fffb7f &d = 0x7fffb7e &e = 0x7fffb7e

int * iptr, * jptr; double * dptr, * eptr; iptr = &i; jptr = &j;

// value of iptr is address of i // value of jptr is address of j dptr = &d; // value of dptr is address of d eptr = &e; // value of eptr is address of e cout << "&i = " << iptr << endl << "&j = " << jptr << endl << "&d = " << dptr << endl << "&e = " << eptr << endl; }

// store addresses of doubles

Example

Dereferencing

* is the dereferencing (or indirection ) operator

It can be used to access the value stored in a location.

For an expression of the form

  • pointerVariable

the value produced is not the address stored in

pointerVariable but is instead

the value stored in memory at that address.

Value of dptr: 0x7fffb7e

*dptr

We say dptr points to that memory location

(whose address is 0x7fffb7e8)

Value of *dptr: 3.

A dereferenced pointer is a variable and can thus be used in the same way as all variables of the type to which the pointer is bound

Recall the C++ function to exchange the values of two int variables:

void Swap(int & a, int & b) { int temp = a; a = b; b = temp; }

The values of two int variables x and y can be exchanged with the call:

Swap(x,y);

The first C++ compilers were just preprocessors that read a C++ program, produced functionally equivalent C code, and ran it through the C compiler. But C has no reference parameters. How were they handled?

Translate the function to

void Swap(int * a, int * b) { int temp = *a; *a = *b; *b = temp; }

and the preceding call to: Swap(&x, &y);

This indicates how the call-by-reference parameter mechanism works:

 A reference parameter is a variable containing the address of its argument (i.e., it's a pointer variable) and that is automatically dereferenced when used.

Parameter

Argument

A Note About Reference Parameters:

Other uses of Pointers

• Command-line arguments are passed to a main

function main() via two parameters:

• argc (the argument count): an int whose value is

the number of strings on the command line

• argv (the argument vector): an array of pointers

to chars  argv[i] is the address of the ith

character string on the command line

• Value of a function name is the starting address of

that function  i.e., a function is a pointer!

• One fxn can be passed to another as an argument

Named variables are created using a normal variable declaration.

For example, the declaration

int j = 22;

i. constructed an integer (4-byte) variable at memory address

0x7fffb7f0 and initialized those 4 bytes to the value 22; and

ii. associated the name j with that address, so that all

subsequent uses of j refer to address 0x7fffb7f0 ; the

statement

cout << j << endl;

will display the 4-byte value (22) at address 0x7fffb7f.

Named Variables

Dynamic Allocation

Anonymous variables are usually created using the

new operator , whose form is:

new Type

When executed, this expression:

i. allocates a block of memory big enough for an object of

type Type ,

and

ii. returns the starting address of that block of memory.

Type * ptr; ptr

ptr = new Type ; ptr^ Memory for Type value

This program uses the new operator to allocate two anonymous

variables whose addresses are stored in pointer variables dptr

and eptr:

Note 1: We could have performed these allocations as initializations

in the declarations of dptr and eptr:

double * dptr = new double,

* eptr = new double;

anonymous variables dptr

eptr

dptr

eptr

The input values are then stored in these indirectly via the

pointers dptr and eptr:

*dptr

*eptr

Note 1

Note 2: new must be used each time a memory allocation is needed.

double *dptr, *eptr; dptr = eptr = new double;

eptr = new double allocates memory for a double and assigns its

address to eptr.

dptr = eptr simply assigns this same address to dptr; it does not allocate new memory.

*dptr = 3.14159; *eptr = 0.1423; cout << *dptr << " " << *eptr << endl;

What’s output? "Alias problem" dptr

eptr

Note 2

“dangling pointers"

Run-time arrays

Recall that arrays as we know them have their capacities fixed at compile time. For example, array a declared by double a[50]; has exactly 50 elements.

This is adequate if a fixed-capacity array can be used to store all of the data sets being processed. However, this is often not true because the sizes of data sets vary. In this case, we must either:

— Make array's capacity large enough to handle biggest data set — an obvious waste of memory for smaller data sets. or — Change capacity in array's declaration in source code and recompile (yuck!).

It would be nice if the user could specify the capacity of the array at run time and an array of that capacity would then be allocated and used. This is

possible in C++.

The operator new can be used in an expression of the form

new Type [ n ]

where n is an integer expression, to allocate an array with n elements, each of type Type ; it returns the base address of that array.

This allocation occurs when this expression is executed , that is, at run-time, not at compile-time. This means that the user can input a capacity, and the program can allocate an array with exactly that many elements!

n-

Allocating an Array During Run-Time: new gets memory from the heap (as opposed to the stack , which holds global variables, activation records for each function, etc. for that program). This is the main difference between just saying array[n] and using this dynamic allocation (also passing of multidimensional arrays). new replaces free, malloc, and calloc in C.

Docsity.com

Memory Allo-/Deallo-cation

new receives its memory allocation from pool

of available memory called the heap or free

store. It is usually located between a program

and its run-time stack.

Program

statements

Run-Time

Stack

The run-time stack grows each time a function is Heap

called, so it is possible for it to overun the heap

(if main() calls a function that calls a function

that calls a function ... e.g., due to infinite or too

deeply nested recursion) It is also possible for

the heap to overun the run-time stack due to too

many (or too large) new operations.

When the heap has been exhausted, new returns the value 0 (called the null address or null pointer ). Common to picture a null pointer variable using the electrical ground symbol:

Attempting to dereference a null (or uninitialized or void) pointer variable produces a segmentation fault.

So check whether a pointer is null before attempting to dereference it. double dptr = new double;… if (dptr == 0) // check if pointer has null value { cerr << "\n** No more memory!\n"; exit(1); } or use an assertion: (Remember to #include ) assert(dptr != 0);

dptr

Checking for Null