pointers, memory, simple stuff
Posted on 2004-04-07
This isn't to accomplish anything in particular, just playing w/ stuff, really. Here's the code:
int a = 257;
int * pa = &a;
int ar = (int) pa;
char *pNewPa = (char *) ar;
Basically I just wanted to see if I could separate a primitive's memory into bytes. I start with an integer. I picked 257 because it has a 1 in the lowest and second-to-lowest order bytes, so that way if i was able to isolate the second byte, I would be sure(er) that I had done it than if I picked something under 256 and got a 0.
I first tried just incrementing the pointer: pa++;
Well, it must be smart enough to know that this is a pointer to an integer and (incorrectly) assume that I wanted the next memory space past the integer, so it incremented pa by 4 (4 byte integers). So, I did the little presto-chango there to model the pointer as an int, increment the int by 1, and put then cast that as a character pointer. Basically, I wanted to go from the base addy of the integer a up one BYTE, and get that BYTE - hence incrementing the addy by 1 instead of 4 and casting the result as a char pointer rather than another int.
I would then expect, when I printed the value @ this new location, I would get the value of the second-order byte of the integer a. In the case of 257, this would be 1:
00000000 00000000 00000001 00000001 = 257
but, i don't. i get a bus error sometimes, and sometimes i'll get an integer value, but not 1. I have seen 44, 20, and 5 so far.