April 15, 2003

Memory, Pointers

When I declare a variable, I am allocating memory space for its value. When I declare "j", it's pointing to an empty space:

j -> ______

Now, if I say "j = 7", it just so happens that that empty space that j points to is occupied by the value 7:

j -> 7

Now, if I say "k = j", the system looks up the value for j by seeing what value is in j's memory space, and then assigns it to k's memory space by copying it.

k -> 7

But if I wanted a variable "ptr" to point to the same memory space as k, I'd have to do something different: ptr = &k;

ptr now refers to the memory address of k, so if I were to try to print out ptr itself, it would print out some sort of crazy hexadecimal address location. *ptr is what looks up the value in that address.

ptr = &k;
(*ptr == k;)

The asterisk (*) "dereferences" the pointer. Note that you can also find the address location of ptr by doing &ptr!

SO, in review:

1. var = 2
2. var2 = &var;
3. var3 = *var2;
4. var4 = &var2;

var2 is the address of the memory where "2" is stored. var3 looks up that address and finds its value, currently "2". var4 is the address of var3, which is different than the address of var!

This is why I didn't learn C. It struck me as stupid. Which I guess is partly right, given that so many other languages have been written that didn't even try to deal with this crap.

Posted by Curt at April 15, 2003 02:38 AM

Comments

Modern languages didn't do away with it: Objects are direct descendants of pointers. Just think about what a=b does to ints as opposed to Strings. Basically, every time you're unsing an object, you're actually using a pointer to that object.

Obj1 = Obj2 will have both objects point to the same memory space in the system. However intA = intB will copy whatever value is in intA into intB's memory space.

Posted by: Baumi at April 15, 2003 02:02 PM
Post a comment









Remember personal info?