An Intro to Pointers
Pointers are a great struggling point among peopple trying to the C/C++. There is an aura surrounding them implying that they are only something that true Gods can understand (which is obviously not true). When one uses an int or char or whatever, the value stored at the address of it is the actual value of the variable. However, pointers are different. Instead of holding a value, pointers hold a memory address. This means that if you do not dereference it, you will get the address that it points to. However, using the dereference operator (the little star thing that you always see… it looks like this: *), one can access the value that is in the address that is being pointed to by the pointer (try saying that 3 times fast). This means that the type of the pointer must be the same as the type of data you plan to access (unless you are using void pointers, where you can cast (Don’t worry about this now)). To get the actual address of the pointer, one must use the & (address of) operator. Here is some sample code to demonstrate this: (note, this code uses C++ output mechanisms and can be easily converted to C)
Code:
#include <iostream>
using namespace std;
int main(void)
{
int *foo; //declares a pointer to an int
foo=new int; //means that foo points to an int on the heap or free store (same thing, 2 different names)
*foo=4; //the address that foo is pointing too will now hold a value of 4
// Now here is where it all comes together
cout<<”The address of the pointer is “<<&foo<<”.”<<endl
<<”The address the pointer is pointing to is “<<foo<<”.”<<endl
<<”The value that is held in the address that the pointer is pointing to is “<<*foo<<”.”<<endl;
cin.get();//pause the program
delete foo;
return 0;
}
Another big feature of pointers is that you can make them point to other variables. In doing this, you can indirectly access a different variable. This allows you to manipulate the variable through the pointer. Take this example:
Code:
#include <iostream>
using namespace std;
int main(void)
{ int* foo;//again, we have a pointer to an int
int number;//just a regular int
foo= &number;//foo now points to number's address
//now, any change to foo will also change number
number=5;
cout<<"The address that number is at is "<<&number<<endl;
cout<<"This address being pointed to by foo "<< foo<<endl;
cout<<"number= "<<number<<endl;
cout<<"(accessed through foo) number= "<< *foo<<endl<<endl;
number=2;
cout<<"number= "<<number<<endl;
cout<<"*foo= "<<*foo<<endl<<endl;
*foo=10;
cout<<"Number= "<<number<<endl;
cout<<"*foo= "<<*foo<<endl;
cin.get();//pause the program
return 0;
}