Question:
Why was sample divided into char sized data? And when pointer arithmetic is performed, how was it able to get its remaining value? How this was possible?
&sample: 0022FF6F ptrUint: 0022FF6F
sample: 00000008 *ptrUint: 22FF6F08 <- Problem Point
Question:
Why is it that there is a garbage value in *ptrUint? Why does the garbage value similar to ptrUint? How do you remove the garbage value in the first place?
Sorry, I was not able to add "&" in the post. I will not be able to show you the output if I screwed up, because there is a casting error which prevents compilation. Anyways, I was wondering
if pointer variables has a different take in data widening. For, example:
Anyways, I was wondering if pointer variables has a different take in data widening
Kind of... yeah. The thing that's different is that pointers don't widen the variable. They just read from the memory you give them.
When you allocate space for an unsigned char, that gives you 1 byte of memory. If you cast the pointer so the compiler thinks it's pointing to an int, it will attempt to read 4 bytes from memory. However only 1 of those bytes is the char... the other 3 are garbage (or possibly values from other variables).
// let's say that this is some random block of memory:
// FF EE FF EE FF EE FF EE
// we allocate one byte:
unsignedchar b;
// the compiler decides to put b here:
// FF EE FF EE FF EE FF EE
// ^
// b
// change the value of b:
b = 8;
// since 'b' is only 1 byte wide, this only changes
// 1 byte of memory:
// FF EE FF 08 FF EE FF EE
// ^
// b
// now if we do some nasty pointer stuff:
unsignedint* p = (unsignedint*)(&b);
// now p points to the same memory that 'b' uses
// to see, we can print it:
cout << hex << *p;
// since sizeof(*p) is 4 bytes, this prints 4 bytes of memory
// starting from address p:
// FF EE FF 08 FF EE FF EE
// ^^ ^^ ^^ ^^
// b
//
// so FFEEFF08 is printed