For the record... this is something you should
never ever ever do.
Also.. you're doing it wrong. You probably meant do to this for line 11:
|
unsigned int p_array = (unsigned int)array;
|
At least... if you're trying to do what I think you're trying to do. I'm going to assume that for the rest of this post.
As for your question:
- line 10 makes an array of 30 integers.
- line 11 makes an integer and assigns it to the
pointer of the array. Since a pointer is an address (represented by an integer), the pointer can be stored in an integer type. For example you can code like the following as a more simplified test:
1 2 3 4 5 6
|
char buf[2];
unsigned a = (unsigned)&buf[0];
unsigned b = (unsigned)&buf[1];
cout << a << endl;
cout << b << endl;
|
You'll note that 'b' will always be a+1, because the address of buf[1] is 1 higher than buf[0]
But anyway... the point is that 'p_array' really contains a pointer, even though its type is an int.
- one line 15, you then cast p_array to a test* (a different kind of pointer). Again since a pointer is basically just an integer, this can be done. Effectively, you're making 'Test1' point to 'array'. The same thing can be accomplished with the following:
1 2
|
unsigned int array[30];
test* Test1 = (test*)array;
|
The only difference in your code is you're running the pointer through 'p_array' instead of assigning it directly.... kind of like this:
1 2 3 4 5
|
int a, b;
int p_array;
p_array = a;
c = p_array;
|
- In
THEORY sinceee 'test' is just a structure of integers, those integers are layed out in the same way as an integer array. Therefore on line 17, doing 'Test1->a' really gets you 'array[0]' because Test1 points to array. 'Test1->b' gets you array[1], etc.
But note that
this is not always the case because the compiler is free to rearrange and pad the structure as it sees fit, so there is no guarantee that this code will always work.
Hence why you should never, ever, ever, ever,
EVER do this.
EDIT: too slow. doh! ^^