pointers:
Think of a variable like a home. It has an address, and it holds things. A pointer is basically a forwarding address to the house. So you can access the house by the address that the pointer holds.
</bad analogy>
Now how is this useful in code? There are tons and tons and tons of ways that pointers are useful.
one such way is for efficiency. For example:
say we had a function, one that acted on a variable that stored a TON of data. Well if we just pass the variable in like normal, the variable is actually
copied for that instance of the function:
1 2 3 4 5 6 7 8
|
int addall(BIGVAR bv){
for (int a = 0; a < bv.size(); a++){
static int e = 0; //This is kind of a side lesson, if you make a static variable, it doesn't die
//when the scope changes like normal variables do.
e += bv[a];
}
return e;
}
|
In the previous function, we actually made a copy of bv. Now this isn't super important when you're just working with variables like int's and char's and such, but say you had a 100 page document stored in a string or a vector<char>, then it get's pretty bad making a deep copy.
Another Reason Pointers Are Awesome(also applies to references, actually mostly references):
Say we had a variable that happened to be Really large, and we want to change small parts of it, with a function or a method. Well without pointers, we'd just say
myvar = function(myvar);
, which is (AFAIK) making
two deep copies of your object. However if you use a pointer, you don't have to copy it ever! you can just say
function(myvar);
. Now I'm sure that makes no sense to you, so here's an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
//Using ints showing the usage of a pointer.
int dbl(int orig){ //Deep copy.
return orig * 2;
}
void dbl(int* orig){ //Shallow copy.
(*orig) *= 2; //(*var) is a dereference. or accessing the variable at the address of the pntr.
}
int main(){
int number = 12;
int othernumber = 12;
///First, let's double the "number" variable
number = dbl(number);
//"number" now holds 24.
///Now, let's double the "othernumber" variable
dbl(&othernumber);
//This second double is passing in the address of "othernumber" an address and a pointer
//are close to synonymous. Here's how you would do this with a pointer variable:
int* inptr = &othernumber; //Making a new int pointer, and making it point to "othernumber"
dbl(inptr);
//this third example produces EXACTLY the same results as the other examples.
//you can access the variable pointed to by a pointer by DEREFERENCING it:
if((*inptr) == othernumber){} //ALWAYS(well maybe not) returns true,
//because they are the same! =]
}
|
Of Course
These aren't the only uses of pointers, but they are at least two really useful and cool things you can do with pointers. As you program and come up with more and more complicated programs, you'll learn to love them!
Any Questions?