Tuesday, September 28, 2010

I see now

I know why it works now.

Lesson 1: Pointers are nice because they let you manipulate variables outside of the function you happen to be in.

Lesson 2: Pointers are nice because they let you manipulate pointers outside of the function you happen to be in.

Lesson 3: I need to stop treating pointers like they're not variables.

I got this to work by more or less following examples in the book, but now I realize why it works.

I had a pointer: FILE *plxfilepointer

plxfilepointer doesn't point to anything yet. It's (probably) NULL, I don't know if it gets specifically set to that or if I have to do it manually.

I can't pass the pointer to the function that opens the file. Well... actually I can, but it gets passed by value and the local function's pointer dies when the function ends.

So, what I did instead was pass the address of the pointer - that is NOT to say the address the pointer contains, but the actual address in memory of where the pointer is. That was what lesson 3 above means. A pointer is a variable that holds a memory address that has its own memory address. I didn't NOT know that, it's just easy to forget when push comes to shove in the code.

Ok, so I pass my function the address of my pointer: loadfile(&plxfilepointer)

Here is the part that I finally understand: an integer holds an integer and has its own memory address, and a pointer holds the memory address to another place in memory and also has its own memory address. What holds the memory address of a pointer and also has its own memory address? A pointer to a pointer. So, the proper variable to pass the memory address of a pointer to is a pointer to a pointer.

So, the loadfile() prototype is:

void loadfile (FILE **a)

**a is a pointer to a pointer, and when I pass it &plxfilepointer it pointers to plxfilepointer, which we want to hold a memory address to our file.

inside loadfile is: *a = fopen("test.plx", "rb");

Ah, so if I dereference a pointer to a pointer, I get the value of the pointer I point to, so I can set the pointer I point to to anything I want - in this case the memory address of the file I loaded. There has to be a better way to say that.

So when the function is over, what is destroyed? Only my pointer to the pointer.

I got this to work with trial and error (and lots of sketching) last night, and I was super upset that it worked without me knowing why it worked. I had to go to bed before I could figure that out, but I figured it out just laying in bed and focusing. That's good - it probably means I'm committing a lot of what I'm learning to memory.

The punchline: I need to stop treating pointers like magic, and I need to not get tripped up by the asterisks. Oh, and I'd have never made it work in the first place if I hadn't drawn out what was happening in memory.

No comments:

Post a Comment