Ponter Tutorial


About the Author

General Programming




Visual Basic


JAVA Script



C Graphics ] C Math ] C Misc ] Common C&C++ Pitfalls ] [ Ponter Tutorial ]

What's a pointer?

A pointtr is a var that stores a memory location.
To declare a pointer, first you must tell the compiler the size of the memory location the pointer is pointing at. For example, if you want to use a pointer to integer, you have to declare:
int *p; This means that p stores a memory address of 2 bytes.
When you use a pointer var, the memory allocated is take it from the heap, and when you use an var type like int x; the memory allocated is from the program stack, so it's better to use pointers for some cases. (Lets say the stack is the memory reserved for the program data, and the heap is the rest of memory available).

Using pointers.

I will show this with an example.

int x,y; x,y are integers
int *p; p is a pointer to integer (2 bytes)
//now, to makes p points to x mem location, u use the indirection symbol: &

p=&x; //this means that p stores the x address
//and now let's use p to do x=y; (stupid but shows the concept)

y=*p; //the symbol * tells the compiler to take the value in the address that is stored in p.

//so, y now is 10
//be careful, using * and & incorrectly, may crash your program:

y=&p; //this is not correct!
p=*x; //this is not correct!

Just remember, & means "the address of", and * means "the data stored in the address".

Pointers and structs

You can make a pointer to point a struct. This reduce the amount of memory needed from the stack.

struct Points{
int x;
int y;

//now we declare a var of the struct type
Points Point;

//a pointer to struct
Points *p;

//to use the struct fields, we use this indirection symbol: ->


//so, since p points to Point, we have that Point.x is = 120

Now, sometimes, we have a huge struct and the memory is not enought to allocate it in the stack.
So, we can use pointers to allocate the struct in the heap. To allocate this memory, we use the operator: new.

Points *q;
q=new Points;

//now, u can do this

Void pointers

Void pointers can't be deferenced without use casting. Using casting tells the compiler the size of the var that the pointer is pointing at.

int x;
float y;

void *p; //void pointer
p=&x; //points to var x
*p=12; //incorrect! the compiler doesn't know the size of pointed data (because the pointer is declared as void)

*(int *)p=12; //correct, we are telling the compiler that p is pointing to a int * type (pointer to integer)

*(float *)p=123.24;

//As you can see, the same pointer can be used to point to different data types.

Without void pointers, we must declare 2 pointers.
int *p; //to points to x
float *q; //to points to y


Link of the week 

This page is best viewed in 800x600x256. This page was last edited Saturday, July 15, 2000