Hipo posted:
Hi.
I have the following code:
unsigned char temporary[160];
unsigned __int64 *reader = (unsigned __int64*)&temporary+20;
That line behaves identically to:
unsigned __int64 *reader = reinterpret_cast<unsigned __int64 *>(
reinterpret_cast<char *>(temporary) + sizeof(unsigned __int64[20])
);
"reader" now points to the first byte AFTER the last element of
"temporary". Try changing that 20 to 12:
unsigned __int64 *reader = reinterpret_cast<unsigned __int64 *>(
reinterpret_cast<char *>(temporary) + sizeof(unsigned __int64[12])
);
std::cout << *reader-- << std::endl;
std::cout << *reader-- << std::endl;
std::cout << *reader-- << std::endl;
Two caveats:
(1) Beware of trapping bits.
(2) You're deallocating the pointer to one BEFORE the array.
Try the following code:
#include <iostream>
#include <ostream>
#include <cstdlib>
enum { quantity = 20 };
int main()
{
typedef unsigned __int64 uint64;
uint64 big_numbers[quantity] =
{ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,
11,12,13,14,15,16,17,18,19,20 };
unsigned char temporary[160];
/* That would be better written as:
unsigned char temporary[ sizeof(uint64[quantity]) ]; */
std::memcpy(temporary, big_numbers, sizeof( big_numbers ) );
for(uint64 *reader = reinterpret_cast<uint64*>(
reinterpret_cast<char *>(temporary)
+ sizeof(uint64[20])
);
reader-- > reinterpret_cast<uint64*>(temporary);
/* No action */ )
{
std::cout << *reader << '\n';
}
std::system("PAUSE");
}
-Tomás