



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!




std::sort( a, a+n )
sorts the values in the array into increasing order.
int x; double y;
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.
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.
What is the output of the following code? Be sure to draw a picture of the stack and the heap to help you figure it out.
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;
int main() { cout << "Enter the size of the array: "; int n; cin >> n; double *a = new double[ n ];
int i; 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; }
double *a = new double[ n ];
a[i] = sqrt( i );
*(a+i)
which we saw in Lecture 4.
delete [] a;
releases the memory allocated for the entire array. Without the [], only the first double would be released.
(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.
#include
int main( int argc, char* argv[] ) { // Check the number of command-line arguments if ( argc != 2 ) { cerr << "Usage:\n " << argv[0] << " n\n" << "where n is a positive integer\n"; return 0; }
// Take n from the 1st argument by converting the string to an // integer. Make sure it is positive. int n = atoi( argv[1] ); if ( n <= 0 ) { cerr << "Usage:\n " << argv[0] << " n\n" << "where n is a positive integer\n"; return 0; }
// Start here...
return 0; }