



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!




Reading: Ford & Topp, pp. 219-
Consider the following code segment:
float x = 15.5; float *p; p = &x; *p = 72; if ( x > 20 ) cout << "Bigger\n"; else cout << "Smaller\n";
The output is
Bigger
because x == 72.0. What’s going on?
p = &x;
Takes the address of x’s memory location and stores it (the address) in the memory location associated with p.
*p = 72;
causes the computer to get the memory location stored at p, then go to that memory location, and store 72 there. This writes the 72 in x’s location.
What is the output of the following code sequence?
int x = 10, y = 15; int *a = &x; cout << x << " " << y << endl; int *b = &y; *a = x * *b; cout << x << " " << y << endl; int *c = b; *c = 25; cout << x << " " << y << endl;
if ( p != 0 ) cout << *p << ’\n’
tests to see if p is pointing somewhere that appears to be useful before accessing the value stored at that location.
const int n = 10; double a[n]; int i; for ( i=0; i<n; ++i ) a[i] = sqrt( double(i) );
const int n = 10; double a[n]; int i; for ( i=0; i<n; ++i ) a[i] = sqrt( double(i) );
can be rewritten as
const int n = 10; double a[n]; double *p; for ( p=a; p<a+n; ++p ) *p = sqrt( p-a );
p = a;
takes the address of the start of the array and assigns it to p.
The line p=a could also have been written:
p = &a[0];
which means “find the location of a[0] and take its address”.
*p = sqrt( p-a )
p-a is the number of array locations between p and the start. This is an integer. The square root of this value is assigned to *p.