Exercise 3-24 (Pointer arithmetic for long and long double)
Chapter_3 Exercise_3-23 PointerArithmetic | DynamicDebugFlags Exercise_3-25 |
Exercise 3-24 TCP1, p. 229
Exercise 3-24. Modify PointerArithmetic.cpp (see ch3-PointerArithmetic) to work with long and long double.
PointerArithmeticLongDouble.cpp download
#include <iostream>
using std::cout;
using std::endl;
#define P(EX) cout << #EX << ": " << EX << endl; // print
int main()
{
long a[10];
long double b[10];
for(int i = 0; i < 10; i++)
{
a[i] = i+10;
b[i] = i+20;
}
long* lp1 = a;
P(*lp1) // 10 (first element)
P(*++lp1) // 11 (lp1 points now to second element)
P(lp1 - a) // no of elements between the two pointers (1)
P(a - lp1) // no of elements between the two pointers (-1)
P(*(lp1 + 5)) // 16 (seventh element)
long* lp2 = lp1 + 5;
P(*lp2) // 16
P(*(lp2 - 4)) // 12 (third element)
P(*--lp2) // 15 (lp2 points now to sixth element)
P(lp2 - lp1) // no of elements between the two pointers (4)
P(lp1 - lp2) // no of elements between the two pointers (-4)
cout << endl;
// long double* ldp1 = a; // compile error: cannot convert long to long double
long double* ldp1 = b;
P(*ldp1) // 20 (first element)
P(*++ldp1) // 21 (ldp1 points now to second element)
// P(ldp1 - a) // compile error: cannot compare long and long double pointers
P(ldp1 - b) // no of elements between the two pointers (1)
P(b - ldp1) // no of elements between the two pointers (-1)
P(*(ldp1 + 5)) // 26 (seventh element)
long double* ldp2 = ldp1 + 5;
P(*ldp2) // 26
P(*(ldp2 - 4)) // 22 (third element)
P(*--ldp2) // 25 (ldp2 points now to sixth element)
P(ldp2 - ldp1) // no of elements between the two pointers (4)
P(ldp1 - ldp2) // no of elements between the two pointers (-4)
return 0;
}
/*
g++ PointerArithmeticLongDouble.cpp -o PointerArithmeticLongDouble
./PointerArithmeticLongDouble
*lp1: 10
*++lp1: 11
lp1 - a: 1
a - lp1: -1
*(lp1 + 5): 16
*lp2: 16
*(lp2 - 4): 12
*--lp2: 15
lp2 - lp1: 4
lp1 - lp2: -4
*ldp1: 20
*++ldp1: 21
ldp1 - b: 1
b - ldp1: -1
*(ldp1 + 5): 26
*ldp2: 26
*(ldp2 - 4): 22
*--ldp2: 25
ldp2 - ldp1: 4
ldp1 - ldp2: -4
*/
Chapter_3 Exercise_3-23 PointerArithmetic | BACK_TO_TOP | DynamicDebugFlags Exercise_3-25 |
Comments
Post a Comment