Thread: pointers
View Single Post
Old Jul 12th, 2005, 1:40 AM   #7
Mad_guy
Hobbyist Programmer
 
Mad_guy's Avatar
 
Join Date: Oct 2004
Location: Sandstorm, Techno Club
Posts: 239
Rep Power: 5 Mad_guy is on a distinguished road
Send a message via AIM to Mad_guy Send a message via MSN to Mad_guy
You should learn to use pointers well, they are quite the handly little bastards.


You can also find a good use for them by doing Dynamic memory allocation. Which is useful, while you're learning it you'll also find all sorts of ways to crash the hell out of your computer and make it run slow by not freeing up memory.

This is in an old C tutorial I read when I started, let's say you have two variables, a and b, they both hold an integer, let's say you want to flip the values, and you're going to do this a lot, and you want to make a function to do it, so you come up with this:

void flipflop(int a, int b)
{
 int tmp = a;
 a         = b;
 b         = tmp;
}

Looks fine, but it doesn't work? Oh noes! This is because the lexical scope of the variables a and b are limited ONLY to that function. You have two options here:

1. Use globals
2. Use pointers with the function

Second way is easier, and you'll come out with something like this:

void flipflop(int *a, int *b)
{
 int tmp = *a;
 *a   = *b;
 *b   = tmp;
}

Then you could do:

int a = 4, b = 5;
flipflop(&a,&b);

And you flip them.
Mad_guy is offline   Reply With Quote