|
![](/i/fill.gif) |
Hello, I'm studying C++ on my own and would appreciate some help.
In the following Program:-
#include <iostream>
using namespace std;
const int sz = 100;
struct X { int a[sz]; };
void print(X* x) {
for(int i = 0; i < sz; i++)
cout << x->a[i] << ' ';
cout << endl << "--------------------" << endl;
}
int main() {
X x;
print(&x);
int* xp = reinterpret_cast<int*>(&x);
for(int* i = xp; i < xp + sz; i++)
*i = 0;
print(reinterpret_cast<X*>(xp));
} ///:~
I don't understand this line:
**** print(reinterpret_cast<X*>(xp)); ****
why do you pass 'xp' into the cast but not '&xp'....?
Because earlier you need to pass the address of x into the cast:
**** int* xp = reinterpret_cast<int*>(&x); ****
Please help me cos i've been thinking about this for so unnecessarily long.
Cheers, Tim.
Post a reply to this message
|
![](/i/fill.gif) |
|
![](/i/fill.gif) |
Tim Chan wrote in message <3bfbf514$1@news.povray.org>...
>Hello, I'm studying C++ on my own and would appreciate some help.
[program snipped]
>I don't understand this line:
>
>**** print(reinterpret_cast<X*>(xp)); ****
>
>why do you pass 'xp' into the cast but not '&xp'....?
xp is of type pointer to int, and you are converting it to the type pointer
to X. &xp would be the address of xp, and would be of type pointer to
pointer to int.
>Because earlier you need to pass the address of x into the cast:
>
>**** int* xp = reinterpret_cast<int*>(&x); ****
Here, x is of type X. &x is the memory address of x, and is of type pointer
to X. The reinterpret_cast converts that to type pointer to int.
--
Mark
Post a reply to this message
|
![](/i/fill.gif) |
|
![](/i/fill.gif) |
Tim Chan <tim### [at] blueyonder co uk> wrote:
: #include <iostream>
: using namespace std;
: const int sz = 100;
: struct X { int a[sz]; };
: void print(X* x) {
: for(int i = 0; i < sz; i++)
: cout << x->a[i] << ' ';
: cout << endl << "--------------------" << endl;
: }
: int main() {
: X x;
: print(&x);
: int* xp = reinterpret_cast<int*>(&x);
: for(int* i = xp; i < xp + sz; i++)
: *i = 0;
: print(reinterpret_cast<X*>(xp));
: } ///:~
I know I'm replying to a rather old message, but this code looked so
horrible, that I must reply.
Firstly I think that it breaks the standard. One cannot assume that
the member variables of a struct start right at the beginning of the
struct.
Secondly, why not just:
int main() {
X x;
print(&x);
for(int i = 0; i < sz; ++i)
x.a[i] = 0;
print(&x);
}
It's a lot nicer, doesn't use hacks and doesn't break the standard.
--
#macro N(D)#if(D>99)cylinder{M()#local D=div(D,104);M().5,2pigment{rgb M()}}
N(D)#end#end#macro M()<mod(D,13)-6mod(div(D,13)8)-3,10>#end blob{
N(11117333955)N(4254934330)N(3900569407)N(7382340)N(3358)N(970)}// - Warp -
Post a reply to this message
|
![](/i/fill.gif) |