


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 15
Today’s Lecture — Pointers and Dynamic Memory
16.1 Three Types of Memory
16.2 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;
16.3 Exercise
double * p = new double; *p = 35.1; double * q = p; cout << *p << " " << *q << endl; p = new double; *p = 27.1; cout << *p << " " << *q << endl; *q = 12.5; cout << *p << " " << *q << endl; delete p; delete q;
16.4 Dynamic Allocation of Arrays
int main() { cout << "Enter the size of the array: "; int n,i; cin >> n; double *a = new double[ n ]; for ( i=0; i<n; ++i ) a[i] = sqrt( i ); for ( i=0; i<n; ++i ) if ( double(int(a[i])) == a[i] ) cout << i << " is a perfect square " << endl; delete [] a; return 0; }
16.7 Dynamic Allocation Example: The Sieve of Eratosthenes, Revisited
// Using Sieve of Eratostenes determine all prime numbersless than or // equal to an integer provided on the command line. #include
int main(int argc, char* argv[]) { // Check usage. Take n from the 1st argument. Make sure it is positive. if (argc != 2) { cerr << "Usage:\n " << argv[0] << " n\n" << "where n is a positive integer\n"; return 0; } int n = atoi(argv[1]); if (n <= 0) { cerr << "Usage:\n " << argv[0] << " n\n" << "where n is a positive integer\n"; return 0; }
// Create and initialize a dynamically allocated array bool * is_prime_sieve; is_prime_sieve = new bool[n+1]; int i; is_prime_sieve[0] = is_prime_sieve[1] = false; for (i=2; i<=n; ++i) is_prime_sieve[i] = true;
// Check each integer up to n to see if it is prime. Output those that are. int prime_count = 0; for (i = 2; i <= n ; ++i) { // If a number is not prime, then we can skip it. if (is_prime_sieve[i]) { cout << i << " is prime\n"; ++prime_count; // No multiples of i are prime. Mark these multiples in the array. for (int j = 2*i; j <= n; j += i) is_prime_sieve[j] = false; } } cout << "\nThere are " << prime_count << " primes <= " << n << endl;
// Release the dynamic memory through the delete operator delete [] is_prime_sieve; return 0; }
16.8 Exercise: Dynamic Allocation Arrays vs. Vectors