Exercise 3-23 (PointerIncrementUnion)
Chapter_3 Exercise_3-22 PointerIncrement | PointerArithmetic Exercise_3-24 |
Exercise 3-23 TCP1, p. 229
Exercise 3-23. Modify PointerIncrement2.cpp (see ch3-PointerIncrement) so it uses a union instead of a struct.
PointerIncrementUnion.cpp download
#include <iostream>
using std::cout;
using std::endl;
typedef union
{
char c; // sizeof(char) = 1 byte
short s; // 2 bytes
int i; // 4 bytes
long l; // 8 bytes
float f; // 4 bytes
double d; // 8 bytes
long double ld; // 16 bytes
} Primitives; // 16 bytes (largest member)
int main()
{
Primitives p[10];
Primitives* pp = p;
cout << "sizeof(Primitives) = " << sizeof(Primitives) << endl;
cout << "p = " << (long)p << endl;
cout << "pp = " << (long)pp << endl;
// p++; // compile error: not lvalue
pp++;
cout << "After increment:" << endl;
cout << "p = " << (long)p << endl;
cout << "pp = " << (long)pp << endl;
// p--; // compile error: not lvalue
pp--;
cout << "After decrement:" << endl;
cout << "p = " << (long)p << endl;
cout << "pp = " << (long)pp << endl;
cout << "p+2 = " << (long)(p+2) << endl;
cout << "pp+2 = " << (long)(pp+2) << endl;
cout << "p-1 = " << (long)(p-1) << endl;
cout << "pp-1 = " << (long)(pp-1) << endl;
return 0;
}
/*
g++ PointerIncrementUnion.cpp -o PointerIncrementUnion
./PointerIncrementUnion
sizeof(Primitives) = 16
p = 140723180902672
pp = 140723180902672
After increment:
p = 140723180902672
pp = 140723180902688
After decrement:
p = 140723180902672
pp = 140723180902672
p+2 = 140723180902704
pp+2 = 140723180902704
p-1 = 140723180902656
pp-1 = 140723180902656
*/
Chapter_3 Exercise_3-22 PointerIncrement | BACK_TO_TOP | PointerArithmetic Exercise_3-24 |
Comments
Post a Comment