pointers

Started by
2 comments, last by Spoonbender 17 years, 9 months ago
I understand how to use pointers it's just that i don't know what the reason is for using them. What situation would i need a pointer???
##########################################################You'll have time to rest when you're dead - Robert De Niro
Advertisement
Some data structures use pointers, a simple yet perhaps slightly complex(for beginners) example is a linked lists. There is other uses for them as well such as arrays, I am sure you are familiar with the concept of an array, if not I suggest you look into them. Basically you could define an array such as:
int array[50];

Now what does this do? It creates an area in memory that there contains the bytes for the number of integers specified. Now if you were to simply print out the variable as array, through something like:
cout << array << endl;

You would get a address to the location to where the integers are stored. This address is a pointer to that location, so arrays are a very simple example of a pointer in use. So basically when you call array[0] to get the location of the first integer in the array; it will look at the pointer to find its location in memory and return the integer you are asking for.

You can also use them to potentially increase speed of passing arguments. Sending an entire object as a parameter for use is more complicated then simply sending the memory address or pointer, to find it.

Another possibility is callback functions such functions are useful in games. For instance you could have a void * pointer that points to a function in your program. This way when you make your program you could use a predefined object that you just set the render and begin methods through providing the pointer to them. This way you don't need to re code things as often. They really have a lot of uses, it depends on what you want to do.

Does that make sense? Those are just some simple examples I can specify for you that I hope helped.

[Edited by - DevLiquidKnight on July 28, 2006 1:10:16 AM]
A reference or pointer is useful when you must associate an object to another. For instance, an unit U is owned by a squadron S, and you want a cannon C to acquire U as a target. You cannot give a copy of U to C, because U would move independently of its copy and the copy would be damaged independently of U. What you need is for C to reference U. This can be done by giving C a pointer to U, which it can use to track the movement of its target and fire at it.
Just avoid them as long as possible. If you know what they do, then that's fine. When you need pointers, you can start using them, and it'll be clear what the reason is for using them. [grin]

But there's really not much point in going around looking for places to use pointers. Everyone else does the opposite, and goes around trying to avoid them.

This topic is closed to new replies.

Advertisement