Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Microsoft: Visual C++ FAQ


Complete Layman's Guide to Pointers by qednick
Posted: 20 Dec 02

I decided to write this FAQ because I have answered this same question  a few times now (the latest time I spent about 45 minutes writing my response to a student only to discover the student's post red-flagged the day after!). Hopefully, this FAQ will make pointers a little clearer and help students to understand them without running the risk of making a "homework" related post and getting that post red-flagged.

Pointers are one of the most powerful features of C and C++. Unfortunately, they are also one of the hardest things to learn and understand about these languages. Hopefully, I can throw some light on the subject for anyone who is serious about learning C/C++ from a layman's perspective.

What is a pointer?
A pointer is not really a tangible object like your regular run-off-the-mill variables such as int and double, etc. A pointer is simply an address in memory where a variable is stored.
Picture this scenario: you create a simple program in C/C++ and declare a single int which stores a value. That int will [usually] make your program use an extra 4 bytes of random access memory (RAM). Therefore, the more variables you declare in your program, the more RAM your program needs to keep running.
By declaring that int in the program, your computer allocates those 4 bytes of RAM to your program. Those 4 bytes in memory is where your program stores the value of the int. While that int variable is valid (ie. in 'scope' within a function), your program will keep that unique memory address linked to your int. Once the int goes out of scope (eg. at the end of the function containing it), those 4 bytes of memory are then released and can be re-allocated to other variables your program may declare.

Now that you understand about your program's memory, it's time to answer the first question: a pointer is an item that 'points' to a certain address in memory. Knwoing this address means that you can retrieve the 'real' value of the original item that the memory was allocated for in the first place.

How do I use a pointer?
Taking our int example one step further, let's examine a short program:

int main(void)
   // declare an int and set a value
   int   someInt = 18;

   // declare an int 'pointer'
   int*  somePtr = NULL;

   // set out pointer to point to the
   address in memory of someInt

   somePtr = &someInt;

   .. <- check value of somePtr here with debugger!

   return (0);

In the above simple example, we first declare out int and give it a value of 18. We then declare an int pointer by using the 'splat' operator (as I like to call it!). This operator after a variable type name declares the type to be a pointer rather than the actual type itself.
Notice also the ampersand '&' we placed before someInt when we were allocating the address of someInt to somePtr. Placing the ampersand before an object like this is like saying "this is the address in memory of this object - not the value of the object".
One more thing to notice is that when we declared ourr pointer, we allocated a value of NULL to it. The NULL means "address zero" (a 'none address') in computeresque! It is usually a very good idea to "initialize" your pointers to NULL when you declare them if you're not using them immediately! Otherwise, it could be certifiable very bad thing!

What the 'point' in using pointers?
Many beginners (and many Java coders) will be asking this question. Why use pointers at all when you pass the objects themselves as parameters and so? Well, one simple example for use of pointers is that you can only return one value from a function:

int swapValues(int a,int b)
   int temp = a;
   a = b;
   b = temp;
   // <- return a or b here???????

You can see from this simple example that we successfully 'swap' the values of a and b but we reach a stumbling block when it comes to the return value. We can only return 1 value from the function!

By using pointers, we could swap the two values in a separate function without having to return anything at all! For example:

int main(void)
   int a = 27;   // declare our ints and
   int b = 53;   // assign values

   // now call our 'swap' function


   // <-check values of a and b here with debugger!

   return (0);

void swap(int* x,int* y)
   int  temp = *x;
   *x = *y;
   *y = temp;

The first thing to notice is that we used the ampersand '&' sign before the variable names when we passed to our swap function. This is because our swap function is expecting the parameters to be 'pointers' (or the addresses in memory) of ints.
You can see by looking at the parameters of the swap function that this is, indeed, the case because the parameter types are followed by the 'splat' symbol (ie. int*).
However, look inside the function and you'll notice something rather perculiar. We use the 'splat' symbol before the two parameters to get the 'real' value of the two ints! Using this method, we successfully swap over the real values of the two variables.

We do not need a return statement. This is because we are using 'pointers' to objects rather than the real objects themselves. We can do this because the 'real' original ints still exist in memory in the calling function (in this example the calling function is main).

Try pasting the above code into your compiler and you will see that the values are in fact 'swapped' after the call of the function swap().

So why are pointers so powerful?
The above example is just one simple method of using pointers. In the real world, programmers will use pointers to all kinds of objects, structures and classes. You can even use pointers to functions and pass those as parameters - for example, as a "call back" type function.
A prime example of pointer use is in Window messaging. If you've ever come across the Windows API functions PostMessage() or SendMessage() you will have noticed two extra parameters you can use called wParam and lParam. These two parameters are basically void* (void pointers) and this enables you to pass complete structures, objects, text strings or anything you like from one window to another without the need for global variables. This means you can do all this without the memory (RAM) requirements you would otherwise need. It also makes your code look neater!

Another classic example is the Windows call AfxBeginThread() - because a separate thread/process cannot share objects you need to pass in pointers to "prime" the thread with the information necessary. In this case, you first pass the name of the thread function you have written to handle the thread and then you pass a void* of some structure you have created to pass into the thread the information required to control it:

struct myThreadStruct
   char   str[100];
   bool   exitThread;

void SomeFunction(void)
   // our structure is already declared
   // somewhere else (needs to be in scope!)
   // but let's initialize the values so we can
   // retrieve them within our thread function

   strcpy(myInfo.str,"qednick is cool!");
   myInfo.exitThread = false;

   // my info, by the way, is an object of
   // type myThreadStruct

   // spawn a thread here
   CWinThread* myThread = ::AfxBeginThread(myThreadFunct,(LPVOID)&myInfo);

// here's the definition of the myThreadFunct function
UINT myThreadFunct(LPVOID lp)
   // use a typecast to turn the pointer back
   // to type myThreadStruct*

   myThreadStruct*  info = (myThreadStruct*)lp;

   // we can use our myThreadStruct pointer
   // (called "info") to retrieve or even change the
   // values in the original object "myInfo"


   // in this case, the thread will print
   // "qednick is cool!" all over your screen - how fitting!

   return (0);

The thread example is incomplete but it shows how you can pass in a pointer (of any kind) as a parameter and then retrieve it or change it at the other end through the use of typecasting.
We also note something else interesting in our thread function - the -> operator. This is the pointer dereferencing operator. Usually, when you decalre a structure such as our myThreadStruct struct, you access and/or change it's member's values using the '.' (period) operator like so:

myInfo.exitThread = false;

When you are using a 'pointer' to the structure, you use the dereferencing operator in place of the period like this:

myInfoPtr->exitThread = true;

So there you have it - a layman's guide to C/C++ pointers. You've learned what a pointer is (an address in RAM or memory), what the syntax is (the splat, ampersand and dereferencing operator) and you've also learned a couple of small examples as to why pointers are so useful.

Back to Microsoft: Visual C++ FAQ Index
Back to Microsoft: Visual C++ Forum

My Archive

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close