Archived

This topic is now archived and is closed to further replies.

Erlog

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

Recommended Posts

Erlog    122
I''m learning C++ right now, and I''ve been through about 4 or 5 books looking for the answer to my question: What exactly are pointers good for. I have found not one use for them. Could someone please explain where they would be used and especially why they would be used. -Erlog-

Share this post


Link to post
Share on other sites
Ingenu    1629
???
Pointers are the heart.

Sharing data/objects between entities is done via pointers easily.
They are also required to do dynamic memory allocation.
(Well if you don''t use C for that)

-* So many things to do, so little time to spend. *-

Share this post


Link to post
Share on other sites
Krippy2k    134
Well you cannot dynamically create new objects without the use of pointers somehow.

Pointers also minimize overhead when making function calls, etc.

Lets say you have a large complex data structure with 50 variables. If you were to pass the entire structure to a function that operates on it, the calling function would need to copy all of the variables from that structure onto the stack and the called function would need to pop them all back off. This can make things come to a crawl in a hurry.

If you pass a pointer to the function instead, you are only pushing a 32-bit memory address onto the stack and the calling function accesses the data structure that already exists in memory using this address.

Also, if you wanted the function to make changes to the data in the structure that you are passing to it, it can do so easily using a pointer since you are passing the actual address of the current data instead of copying it.

Hope this makes some sense

Seeya
Krippy

Share this post


Link to post
Share on other sites
MadKeithV    992
It could be argued that Java uses nothing BUT pointers (all objects are passed by reference, not by value).

That also makes an excellent case: pointers do not have to be explicitly mentioned in a language. It can be written so that you do not need to understand the concept of pointers to use them to good effect.

For some low-level programming, having actual access to the pointers (as a true memory address), and performing pointer arithmetic, can be very useful.


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.

Share this post


Link to post
Share on other sites
Chronoslade    122
That is why they are slower and not a higher-level language like C\C++. Well refering to BASIC anyways, JAVA is a lot more advanced that BASIC but not as advanced as C++.
When i began learing the C\C++ language I thought the same thing when i started learning pointers. Why do i need to save the address of a variable when i have the variable right here. Now i dont know how i would write some programs without them. Especially when it comes to passing arrays to functions and creating new objects, pointer are invaluable. I will say pointers are one of the reasons C\C++ are so powerful. (but not the only reason)

"There is humor in everything depending on which prespective you look from."

Share this post


Link to post
Share on other sites
Ingenu    1629
JAVA isn''t less advanced than C++. (much more the contrary)
Java is argued to be C++ done right, although I disagree on that I can say that JAVA is very nice to code, and is much less a pain than C++.

They are different, but in their domains they are very advanced.

Yep forgot the problems of vars... but to me it''s data sharing ;p


-* So many things to do, so little time to spend. *-

Share this post


Link to post
Share on other sites
Erlog    122
thanks all, I think I finally understand when, where, how, and why to use pointers. Thanks mostly to krippy''s post, that one helped me the most although, just about everyone''s helped me a teensy weensy bit besides Ingenu''s post that didn''t answer any of the questions that I wrote about at all.

-Erlog-
Thanky!

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
Of course pointers are the heart and power of the language. They give you the ability to directly access and manipulate memory. But I feel that an even simpler analogy is more helpful to those just starting out who may not yet have delved into the darker layers of harware mechanics, digital logic, registers and stacks.

Imagine if you will that you are taking a class in school, and there is only one phhysical textbook available to all the students. When a student "A" needs to use the textbook, he or she must take it down to a copy center, and replicate it. They can then use their own copy. When they are done with it, they must destroy the copy. This already seems like a huge hassle, not to mention a big waste. But lets make it worse. Lets say that student "A" knows that student "B" also needs to utilize the book. It would make sense that "A" could just hand off his copy to "B" and tell "B" to destroy it when they are done with it. But this is not allowed. "B" must take "A''s" copy over to the copy center and replicate. Then both "A" and "B" must destroy their copies when done. The magnitude of this waste of time, paper, and effort grows exponentially as the number of total students increase, and the functional complexity of classwork increases. Pointers remove this kind of problem, in that the original textbook can be referenced/utilized by any student at any time without having to make copies. Simply, the textbook may be made available as a shared resource, or even a web page for that matter. But this does open up a can of worms. I will leave that matter for you to learn on your own.

One final thought.... become very familiar with your debugger. This is your friend, well most of the time atleast

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
while java doesn''t have pointers it has something similar enough that it should be called pointers. They call them references but they have more in common with C++ pointers than with C++ references.

as to the question, you need pointers. It should be obvious. What if you want a creature to know what map tile it is on? It needs a pointer. Using a copy would be wrong, and not just because of memory concerns. Pointers create relationships. You need to understand this if you ever want to be a programmer.

Share this post


Link to post
Share on other sites
jRaskell    220
How about linked lists, stacks, queues, binary trees... all of these require pointers, and pointers are the very root of their flexibility and power.

Share this post


Link to post
Share on other sites
c_wraith    122
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.

Share this post


Link to post
Share on other sites
Krippy2k    134
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

Share this post


Link to post
Share on other sites
Erlog    122
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.

Share this post


Link to post
Share on other sites
granat    122
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

Share this post


Link to post
Share on other sites
MadKeithV    992
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.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
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;
}

Share this post


Link to post
Share on other sites
Kylotan    9859
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.

Share this post


Link to post
Share on other sites
c_wraith    122
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.

Share this post


Link to post
Share on other sites
Krippy2k    134
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

Share this post


Link to post
Share on other sites
Succinct    169
And now, my 2 cents, though I think Erlog's assignment may be due already.

Pointers are a means of accessing a section of memory. Regardless of what that purpose may be -reading, writing, allocating, freeing- all a pointer is to the processer is a 32-bit unsigned value representing an offset in memory (though programmers and the compiler usually treat them quite differently).

My favorite example, the one that opened the door for me with pointers, went kinda like this:

Say you have a structure type, such that the first member of the structure is an integer, and the others are single characters. In some function, you have a local TExampleStructure variable, a pointer for this variable type, and an integer pointer, defined and initialized.

In c/c++ the structure declaration and function definition might look like this:

  struct TExampleStructure
{
int AnInteger;
char Character1;
char Character2;
char Character3;
char Character4;
};

void SomeFunc( void )
{
TExampleStructure ExampleStructure = { 0x41424344,'a','b','c','d' };
TExampleStructure* pExampleStructure = &ExampleStructure;
int* pInteger = &(ExampleStructure.AnInteger)
}


Assume that the ExampleStructure resides at memory address 4000h. pExampleStructure points to the entire ExampleStructure structure and pInteger points to AnInteger. Looking at the pointer variables in a debugger you'll see that even though they were initialzed with seemingly different variables, they have the same value (4000h).

This makes sense if you look at how the structure is allocated in memory (excluding alignment and packing).

        |------------------|------------|---------|
4000h: | ExampleStructure | AnInteger | 4 bytes |
|------------------|------------|---------|
4004h: | | Character1 | 1 byte |
|------------------|------------|---------|
4005h: | | Character2 | 1 byte |
|------------------|------------|---------|
4006h: | | Character3 | 1 byte |
|------------------|------------|---------|
4007h: | | Character4 | 1 byte |
|------------------|------------|---------|


They both just point to whatever is at memory address 4000h. The fact that one is an integer pointer means to interpret its contents as an integer. The TExampleStructure pointer's contents should be treated as a TExample structure.

Remember, a pointer is just a way of accessing memory. It's up to the program to interpret what is actually there.

BTW, this is a very good thread for people getting started with programming in general. I'm going to send a couple of friends here. Good stuff, guys.

Thank you for your bandwidth.
-- Succinct
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~



Edited by - Succinct on July 4, 2001 12:44:31 AM

Share this post


Link to post
Share on other sites