



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




Review from Lecture 5
Added Material, Not In the Printed Notes: Sorting an Array
std::sort( a, a+n )
sorts the values in the array into increasing order.
Today’s Lecture — Pointers and Dynamic Memory
Three Types of Memory
int x; double y;
This allocates space for local variables in functions and eliminates it when vari- ables go out of scope. This memory is allocated on the stack.
static int x;
are not eliminated when they go out of scope. They retain their values, but are only accessible within the scope where they are defined. We will not be discussing these much.
Dynamic Memory
int * p = new int; *p = 17; cout << *p << endl; int * q; q = new int; *q = *p; *p = 27; cout << *p << " " << *q << endl; int * temp = q; q = p; p = temp; cout << *p << " " << *q << endl; delete p; delete q;
int * p = new int;
allocates a new chunk of memory large enough to hold an integer, and stores the memory address of the start of this memory in the pointer variable p.
double *a = new double[ n ];
a[i] = sqrt( i );
*(a+i)
which we have seen several times before.
delete [] a;
releases the memory allocated for the entire array. Without the [], only the first double would be released.
Exercises
(a) dynamically allocate an array of n integers, (b) point to this array using the integer pointer variable a, and (c) then read n values into the array from the stream cin.
(a) Write code to allocate an array of size 2*n, pointed to by integer pointer variable temp (which will become a). (b) Write code to copy the n values of a into the first n locations of array temp.
(c) Write code to delete array a. (d) Write code to assign temp to a.
The code for part 2 of the exercise is very similar to what happens inside the resize member function of vectors!
Dynamic Allocation: Arrays of Class Objects
int n; cin >> n; class foo { public: string a, b; }; foo * farray = new foo[n];
Prime Numbers: Sieve of Eratosthenes