ch3-ReinterpretCast in C/C++

Chapter_3     Exercise_3-14     ConstCast Exercise_3-8     Exercise_3-15







ReinterpretCast     TCP1, p. 185  (reinterpretcast.c,  ReinterpretCast.cpp)




reinterpretcast.c         download


#include <stdio.h> // for printf()

#define SIZE 10

struct X { int a[SIZE]; };

void print(struct X* x);

int main()
{
struct X x;
print(&x);

int* xp = (int*)&x;
int* ip;

for(ip = xp; ip < xp + SIZE; ip++)
{*ip = 0;}

// Can't use xp as an X* at this point unless you cast it back:
// print(xp); // compile error: xp is int*, not struct X*
print((struct X*)xp);
// In this example, you can also just use the original identifier:
print(&x);
}

void print(struct X* x)
{
int i;
for(i = 0; i < SIZE; i++)
{printf("%d ", x->a[i]);}

printf("\n--------------------\n");
}
/*
gcc reinterpretcast.c -o reinterpretcast
./reinterpretcast
-2015726872 32650 755405424 21993 0 0 755404960 21993 2081284944 32766
--------------------
0 0 0 0 0 0 0 0 0 0
--------------------
0 0 0 0 0 0 0 0 0 0
--------------------
*/











ReinterpretCast.cpp         download


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

const int sz = 10;

struct X { int a[sz]; };

void print(X* x);

int main()
{
X x;
print(&x);

int* xp = reinterpret_cast<int*>(&x);
xp = (int*)&x; // C style cast

for(int* i = xp; i < xp + sz; i++)
{*i = 0;}

// Can't use xp as an X* at this point unless you cast it back:
// print(xp); // compile error: xp is int*, not X*
print(reinterpret_cast<X*>(xp));
print(reinterpret_cast<struct X*>(xp)); // C requires `struct' here
print((X*)xp); // C style cast
print((struct X*)xp); // C requires `struct' here
// In this example, you can also just use the original identifier:
print(&x);
}

void print(X* x)
{
for(int i = 0; i < sz; i++)
{cout << x->a[i] << ' ';}

cout << endl << "--------------------" << endl;
}
/*
g++ ReinterpretCast.cpp -o ReinterpretCast
./ReinterpretCast
1926591208 32517 -1017302112 21856 0 0 -1017302752 21856 -1467862800 32764
--------------------
0 0 0 0 0 0 0 0 0 0
--------------------
0 0 0 0 0 0 0 0 0 0
--------------------
0 0 0 0 0 0 0 0 0 0
--------------------
0 0 0 0 0 0 0 0 0 0
--------------------
0 0 0 0 0 0 0 0 0 0
--------------------
*/









Chapter_3     Exercise_3-14     ConstCast BACK_TO_TOP Exercise_3-8     Exercise_3-15



Comments

Popular posts from this blog

Contents