Advertisement

Pointers, what are they good for... - c++

Started by June 28, 2001 07:48 AM
19 comments, last by Erlog 23 years, 7 months ago
How about linked lists, stacks, queues, binary trees... all of these require pointers, and pointers are the very root of their flexibility and power.
Wow... A lot of answers on specific uses for pointers, but no one has mentioned the theory behind them.

Pointers allow programmers to make certain decisions at runtime, rather than when they are writing their code. For instance, what if you had a file that had game data in it... Let''s say monster descriptions. Without pointers, the code would have to look kind of like this:

  monster1 = readMonster();monster2 = readMonster();monster3 = readMonster();  

etc...

You might be protesting that you could use an array instead. But arrays ARE pointers. In C/C++ that''s very explicit, but it''s true in every language with arrays.

Using pointers, though, there are even cleaner ways than using a raw array, which could be allocated too large or too small. One is to use a resizeable array. Another is to use linked lists. Both of those solutions require dynamic memory allocation, in that the amount of memory they''ll end up needing isn''t known at compile time. So pointers are used to keep track of the memory that has been dynamically allocated. In a resizeable array, you just keep a pointer to the beginning of the array, and keep some information on how big the array is. In a linked list, you keep a pointer to a structure, often called a node, which then contains the data you are storing (or a pointer to it), and a pointer to the next node in the list.

In C++, using dynamic allocation could look a lot like this, assuming monsters was some dynamic data structure:

  while (monsterReader->moreMonsters())    monsters->add(monsterReader->readMonster());  


Another case of choosing behaviors at runtime is done with function pointers in C/C++, or inheritence and virtual functions in C++. That''s when, in different circumstances, you might want a function to do different things. The solution is to write the functions for each of those different things, then use a function pointer or virtual invocation to execute the most appropriate one at any given point. This means that the call to the function specified in that way can be done completely generally, without needing to know what the set of circumstances are the leads to each particular function being chosen.

So, from a theoretical standpoint, the purpose of pointers is to allow many kinds of decisions to be made easily at runtime, which is a vitally important ability in programming.
Advertisement
lol
Read first sentence of my reply

I don''t think he is at a point to get into specifics of linked lists and such if he is asking why someone would use a pointer so I did not elaborate on that.

Seeya
Krippy
Actually krip, your post and the anonymous one about text books have been the most helpful yet. Keep them coming, i have a programming assignment that has something to do with pointers, but I don''t really know how pointers would fit in right now. still thinking about it though.
Consider a tilebased game which allows levels to be any size from 100x100 tiles to 1.000.000 x 1.000.000 tiles....

If the level to load is 200x200 then it could use a pointer to allocate space to hold information about 200x200 tiles..When the level is completed the memory is released.
Then the next level is loaded in the same way allocated memory again to hold the information.

If this game did not use pointers it would have to decide what the maximum size of a map could be when the game was written..Lets say 1000x1000 and have an static array like this MapData[1000][1000].

Too bad if a user creates a level of 1200x1200 tiles...The game would crash or refuse to load the level...

Of course this array could be set to 1.000.000 x 1.000.000 but that would be a waste of space in most cases...
That would also mean that people with little RAM could not even play the small levels. Because memory to hold the large maps is allocated always...





Edited by - granat on June 29, 2001 5:45:08 AM
-------------Ban KalvinB !
Pointers made easy ( or at least, easier )


All data in programs uses memory. This is logical, since you cannot store anything without memory. The actual way in which the data uses memory differs between ordinary variables, and pointer variables.

Consider the following two pieces of data:
int i;
int *pI;
The first is a simple integer variable, the second is a pointer to an integer value. What does that mean?
It means that the actual data contained in pI is NOT an integer value, but a Memory Address. It''s a little map that tells the CPU where to look for data.
If I said pI = 0, I wouldn''t be setting an integer to 0, but rather, I''d be pointing at memory location 0 (which, incidentally, is a location you can never use yourself. That''s why most pointers are initialised with the value 0, so you can see that it isn''t really pointing to anything yet).

If the pointer is not pointed to anything meaningful, there''s not a lot you can do at it. It doesn''t really point to an integer value yet. How do you point it to something? Well, there are two possibilities:
1. You can point it to the memory location of an existing integer.
2. You can dynamically create a new integer and point to that.

So what does that mean, really?
For 1, what you do is something like this:
pI = &i
This means, in english:
"Let the integer pointer pI point to the address of integer variable i".
If I''d now do this:
*pI = 25;, it would mean the exact same thing as
i = 25;
This is because *pI now evaluates to i: *pI is the memory location that pI points to.

For 2, the more useful bit, this is what you can do:
pI = new int();
Instead of pointing pI to an existing variable, you''ve just made a whole new one! new int() creates an integer variable at some location, and returns the address of that location.
*pI = 25 would assign the value of 25 to that integer memory location, but there is no integer variable associated with it. The only way to access the 25, is by using pI!
So now you could say:
int answer = i + *pI; and that would be a perfectly valid statement (because *pI evaluates to something with the type of int).


People might not remember what you said, or what you did, but they will always remember how you made them feel.
Mad Keith the V.
It's only funny 'till someone gets hurt.And then it's just hilarious.Unless it's you.
Advertisement
Someone made the following comment up higher in the thread:

>It could be argued that Java uses nothing BUT pointers (all objects are passed by reference, not by value)

The statement in the parantheses is incorrect. Java has only a pass-by-value mechanism and an actual heap-allocated object can never be passed to any function. The only thing ever passed to functions in Java are either scalar/primitives or references. Consider the following code:

public void swap(Object o1, Object o2) {
Object temp = o1;
o1 = o2;
o2 = temp;
}

The effect of this code in Java is absolutely nothing since references are passed by value (no objects are passed). It would be equivalent to the following C++ code:

template
void swap(T* a, T* b) {
T *temp = a;
a = b;
b = temp;
}

So, wouldn''t this last point make it totally impossible to write a ''Swap'' function in Java then? Especially since there are no templates and no preprocessor, as far as I know.
quote:
Original post by Kylotan
So, wouldn''t this last point make it totally impossible to write a ''Swap'' function in Java then? Especially since there are no templates and no preprocessor, as far as I know.


It''s about 99% impossible to write a swap function in java. The exception is when you''re swapping elements inside a known data structure. There are about two times that happens.

  public void swap(int [] A, int i1, int i2){    int temp = A[i1];    A[i1] = A[i2];    A[i2] = temp;}  


And of course all the variants on that using other primitive types of arrays, and Object arrays...

The other time it happens is when you are writing a container class for some data structure, and just write a private swap function giving it two locations in the internal representation of the structure which it will swap.

But the other 99% of the time, a swap procedure isn''t writeable in java.

Strangely enough, I don''t miss it when I''m programming in java, though. It seems I don''t really use swapping all that often except in the above cases.
It is no more difficult to create a swap function for objects in Java than it is in C++ really. Swapping primitives is another story though.

All primitives are passed by value, and all objects are passed by reference. Sort of. If you are passing a primitive, a copy of the primitive is passed to the method. If you are passing an object, a copy of the reference to the object is passed. You cannot do pointer arithmetic or anything like that but when you modify a member of an object you passed to the method, it is modifying the object that already existed similar to working with pointers. The VM does strict checking on this so that you cannot hurt yourself with programmer error.

You can''t do something like this:

void swap( int **i1, int **i2 )
{
int *temp = *i1;
*i1 = *i2;
*i2 = *i1;
}
in java really. But this is just asking for trouble anyways.

And in Java you rarely deal with primitives alone (hence object-oriented), which is why you don''t miss it.

But consider this code:

  public class myInt {  int i;  myInt(int ii) { i = ii; }  static void swap( myInt ref1, myInt ref2 )  {     int temp = ref1.i;     ref1.i = ref2.i;     ref2.i = temp;  }  public static void main(String[] args)   {    myInt x = new myInt(2);    myInt y = new myInt(5);    System.out.println("Before swap x: " + x.i + " y: " + y.i );    swap( x, y );    System.out.println("After swap x: " + x.i + " y: " + y.i );  }}  



Seeya
Krippy

This topic is closed to new replies.

Advertisement