Pointer Variables Basics

Creator:
bfr
Description:
This tutorial demonstrates how to create and use pointer variables and what they're used for (covers the basics).

Pointer Variables

What are they?

Pointer variables are variables that contain another variable's address. Every variable is stored somewherein the computer's memory. One might be stored at 0x120 while another will be at 0x190.

Important Operators

Here are some important operators having to do with the address of a variable: & = The address of * = (In a declaration) pointer to or (In an expression) the thing pointed at by

The & Operator

The & operator returns the address of a variable in the computer's memory. Here is an example:

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std; int main() {
int theVariable;
cout << "Address of the Variable: " << &theVariable << endl;
system("PAUSE");
return 0;
}

The output of this program should look something like:

Address of theVariable: 0x22ff6c Press any key to continue...

The exact address outputted probably won't be the same as the example, but it should be in the same general hex format.

The * Operator

Like I said before, the * operator says in a declaration, pointer to, or in an expression, the thing pointed at by. The following code snippet demonstrates the correct use of *.

int Var;
int* pointerToVar;
pointerToVar = &Var;
//pointerToVar now points to Var
*pointerToVar = 5;
//stores 5 to the addresse of Var

The snippet above demonstrates how to create a pointer variable and then assign a value to an address. When declaring a variable a pointer variable, the syntax is: the type of the variable it points at* variable name The * may appear anywhere between the type declaration and the variable's name. So, you could do:

char* aPointerVariable;

or

char *aPointerVariable;

You can also use pointer variables and the type of a function, like:

double* myFunction(){
//...do some stuff
}

Conclusion

Well, now you should have a grasp over the basics of pointer variables. I could go over offsets and more complex stuff, but then this tutorial would probably be too long, and it's called "Pointer Variable Basics" anyway. I might make a continuation of this though...

Comments

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <b> <u> <i> <hr> <img src <url=
  • Lines and paragraphs break automatically.

More information about formatting options