ch3-PointerArithmetic

Chapter_3     Exercise_3-23 Exercise_3-24







PointerArithmetic.cpp     TCP1, p. 206-207         download


#include <iostream>
using std::cout;
using std::endl;

#define P(EX) cout << #EX << ": " << EX << endl; // print

int main()
{
int a[10];

for(int i = 0; i < 10; i++)
{a[i] = i+10;} // index values + 10

int* ip1 = a;
P(*ip1) // 10 (first element)
P(*++ip1) // 11 (ip1 points now to second element)
P(ip1 - a) // no of elements between the two pointers (1)
P(a - ip1) // no of elements between the two pointers (-1)
P(*(ip1 + 5)) // 16 (seventh element)
int* ip2 = ip1 + 5;
P(*ip2) // 16
P(*(ip2 - 4)) // 12 (third element)
P(*--ip2); // 15 (ip2 points now to sixth element)
P(ip2 - ip1); // no of elements between the two pointers (4)
P(ip1 - ip2) // no of elements between the two pointers (-4)

return 0;
}
/*
g++ PointerArithmetic.cpp -o PointerArithmetic
./PointerArithmetic
*ip1: 10
*++ip1: 11
ip1 - a: 1
a - ip1: -1
*(ip1 + 5): 16
*ip2: 16
*(ip2 - 4): 12
*--ip2: 15
ip2 - ip1: 4
ip1 - ip2: -4
*/





Note:  We do not have to add a semicolon after P(EX) calls in main() as it is part of its definition. For instance, P(*ip1); adds an extra empty or null_statement, with no effect:
cout << "*ip1" << ": " << *ip1 << endl;;









Chapter_3     Exercise_3-23 BACK_TO_TOP Exercise_3-24



Comments

Popular posts from this blog

Contents