Archived

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

Sir_Spritely

RE: Uses for pointers

Recommended Posts

I''ve been researching this now for a month or so and I''ve read more than enough on the topic to last a lifetime. However one question persists in my little head and it won''t go away, so I find the need to ask. Why use pointers? Basically a pointer does exactly the same job(s) as any other variable will do. Only with a pointer it is more effecient and thus saves valuable time upon execution. However your using a pointer to do just what a variable statement could do, why bring in the additional code and use pointers? As an example you might have a variable definition int Pleb = 10. Then to change this you would do Pleb = Pleb +5. Or you could bring in a pointer and do int *ptrPleb = &Pleb. Now with this you would change the value of the variable Pleb by *ptrPleb = *ptrPleb + 5. My whole point is both do exactly the same job right. So why bother bringing in all the additional code just to do the value modification with a pointer when you can easily do the same job with the variable? Seems both pointless and redundant to moi. Anyone got another angle on this? Thanks, Paul.

Share this post


Link to post
Share on other sites
Well, as you''ll probably discover sooner or later, there are a few things in programming you simply couldnt do without pointers. Using a pointer for a single integer variable rarely has any major advantages, but when dealing with large dynamic arrays or structures, pointers will come up often.

Say you have an array of integers, representing test scores (to keep it simple) that you need to average. When you write the code, you don''t know how many test scores every teacher who uses the program will have. With a pointer, you can allocate an array with the size of some other previously inputted number...

int *scores;
//get input from user
scores = new int[numScores];

Then later in your code you could even reallocate it to a second size, or simple delete it with the delete keyword.
As you can see, many serious problems could result in only being able to use staticly sized arrays, and pointers give you a powerful control on memory management.

If you want a second example, let''s say you have a struct with several elements in it that represents some kind of a record that needs to be filled based on user input or some other factor that you can only know during run-time. You would ideally create a function to fill the data elements for you, and to do that you''d need to be able to pass the function the structure you need filled. Passing an entire structure may not be a significant performance hit if it''s small in memory size, but when you''re dealing with a struct or class that has ten thousand vertices and surface normals and all that junk in it, then it can really kill your program by having to pass it to a function whenever you want it changed. As an efficient solution, pointers can be used. You can just have the function accept a pointer, which has a very small size in memory, and access the members with -> notation...ex.

player->x = 0;

Well, I hope that helped, and I hope I just didn''t wrap a bunch of crap that would confuse anyone who reads it. But good luck.

Share this post


Link to post
Share on other sites
Yeah I get it thanks.

Basic pointers are worthless pointers only become like gold dust when used with large arrays, structs or functions. However pointers also only become useful when you start to use the New and Delete keywords. So for simple programs don''t bother with pointers but for more programs using a lot of data use pointers.

Got it, thanks,

Paul.

Share this post


Link to post
Share on other sites
Every night, I ask myself the same question. I had to read the two chapters in my book that discussed them five times to get the concept. Many languages manage to do without them. But some people have lived around pointers so much that they can''t live without them. Even though I understand them, I see very little use for them.

Scott Simontis
Game Programmer in Training
Have a nice day!
Current Project: Waiting for OpenGL Game Programming Book

Share this post


Link to post
Share on other sites
If you're programming C++, there is almost no non-trivial task that you can do without pointers. They are absolutely essential for most advanced data structures, as well as OOP. Even simple tasks require pointers: can you think of a way to copy memory without them? How about passing arrays back and forth between functions?

It's not just that I 'grew up around them', it's that C++ seems to have been designed/evolved around their use. Other languages have different constructs that do many of the tasks that require pointers in C++.

quote:

So for simple programs don't bother with pointers but for more programs using a lot of data use pointers.


No. Don't 'bother' with pointers at all, regardless of the amount of data. If you don't have to use them, don't. However, you will eventually come across many tasks that actually cannot be done without pointers.

[edited by - micepick on May 29, 2003 11:59:12 AM]

Share this post


Link to post
Share on other sites
quote:
Original post by Village Specialton
Many languages manage to do without them.

It''s important to realise that the generalisation of a pointer is the concept of `level of indirection''. That some languages do not directly provide pointers does not mean they omit this important concept. For example, in languages like Java, Python and Lisp, all variables are conceptually pointers, and so can be used to solve the same problems that involve explicitly specifying pointers in C++. In reality, you are using pointers `under-the-hood'', it''s just that C++ forces you to concentrate on such details whether they are relevant to the problem or not.
quote:

But some people have lived around pointers so much that they can''t live without them. Even though I understand them, I see very little use for them.

As an exercise, try creating your own linked-list without using pointers.

Share this post


Link to post
Share on other sites
First, there is whats called stack memory, and heap memory. Stack memory is where the operating system puts all the function call addresses and normal declared variables. Stack memory is limited , i think its 64Kb . using a pointer will allow you to create data objects(a variable is a data object, a structure also..etc) on the heap. The heap is like a huge field of memory for your program to make use of, its usually those 512MB''s or 1GB of RAM that you have.

Using a pointer will allow you to create variables and other data objects on the heap using the new and delete keywords.

Also , consider the following:
struct My Structure
{
double a,b,c,d,e,f,g,h,i,j,k,l;
}

usually a double is 8 bytes on a 32 bit PC. in the above structure you have 12 variables of type double. so thats 12*8= 96 bytes .
If you pass this object to a function, it''s going to be alot slower than just getting a pointer to it, and passing that pointer. the function will still have access to the structure, but what you just did saved you the additional 92 bytes of memory if you had to pass the structure itself since pointers are usually 4 bytes in size. This speed increase will become huge if you have to call the function multiple times or pass multiple structures.

I don''t know if you know this, but when you pass a variable or structure to a function, the OS has to create a copy of that variable or structure on the stack and your function will access that structure, not the original structure you passed. so basically you''re using twice the memory you would have used if you just passed using a pointer.

Share this post


Link to post
Share on other sites
Basically, dont use them until you feel oyu have to. When you''ve programmed in C++ for a short while, you''ll see why pointers are so damn useful. But when you''re doing tutorials or learning from a book or anything like that, the examples are so simple that there really isn''t any reason to use pointers.

But try doing without pointers for now if that feels more natural. Sooner or later you''ll run into something that makes you see why pointers are useful. Until then? Dont worry too much about them :D

---------
Life is like a grapefruit. It''s sort of orangy-yellow and dimpled on the outside, wet and squidgy in the middle. It''s got pips inside, too. Oh, and some people have half a one for breakfast

Share this post


Link to post
Share on other sites
in addition to what everyone else has said i'd like to add this- when you get a bit more advanced, you'll eventually run into function pointers.. which are invaluable. for example, i'm currently using function pointers in my Console and GUI classes.

-eldee
;another space monkey;
[ Forced Evolution Studios ]


::evolve::

Do NOT let Dr. Mario touch your genitals. He is not a real doctor!


[edited by - eldee on May 29, 2003 3:37:08 PM]

Share this post


Link to post
Share on other sites
MANY data structures like linked lists, trees, graphs, forests, etc. can be implemented with pointers. Pointers are used to access memory allocated during runtime. Also pointers are commonly used by functions to change variables of other functions.


main ()
{
int a = 5 ;
int b = 10;

printf ("a: %d\n", a) ;
printf ("b: %d\n", b) ;

swap (&a, &b) ;

printf ("a: %d\n", a) ;
printf ("b: %d\n", b) ;
}

swap (int *aptr, int *bptr)
{
int temp ;

temp = *a ;
*a = *b ;
*b = temp ;
}


In this program the swap function swaps two variables belonging to main . Can u think of another way of doing this without using pointers?

Regards.

Share this post


Link to post
Share on other sites
quote:
Original post by pacman2003
In this program the swap function swaps two variables belonging to main . Can u think of another way of doing this without using pointers?


Yep.

void swap (int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}


[edited by - micepick on May 29, 2003 4:07:51 PM]

Share this post


Link to post
Share on other sites
quote:
Original post by micepick

void swap (int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}


void swap (int &a, int &b)
{
a=a^b;
b=a^b;
a=a^b;
}

Share this post


Link to post
Share on other sites
quote:
Original post by kordova
void swap (int &a, int &b)
{
a=a^b;
b=a^b;
a=a^b;
}

Clever, but I can do it faster:

inline void swap (int &a, int &b)
{
__asm
{
mov ax, a
mov bx, b
mov a, bx
mov b, ax
}
}

It gets rid of those three xors, and no temporary variable on the stack. Yes, I enjoy wasting my time.

[edited by - micepick on May 29, 2003 10:50:44 PM]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster

inline void Swap(int& a, int& b)
{
__asm
{
xor a, b
xor b, a
xor a, b
}
}

i win :-D

Share this post


Link to post
Share on other sites
quote:
Original post by Anonymous Poster
i win :-D

Suuuuure you do.
You''re xoring two locations in memory, which I''m positive is illegal in x86 asm. Even if it isn''t, it''s much much slower than using simple register transferring.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Except I don''t think you can xor two memory locations.

One variable would have to be copied into a register and then copied back.

Share this post


Link to post
Share on other sites
Aha!

inline void swap (int &a, int &b)
{
__asm
{
mov ax, a
xchg ax, b
mov a, ax
}
}


...

OK, I'm done now. No more of this idiocy.

[edited by - micepick on May 29, 2003 11:19:08 PM]

Share this post


Link to post
Share on other sites
This:
quote:

void swap (int &a, int &b){
int temp = a;
a = b;
b = temp;
}



and this:
quote:

inline void swap (int &a, int &b){
__asm
{
mov ax, a
mov bx, b
mov a, bx
mov b, ax
}
}



are the same on 99% of compilers, except you need to use eax and ebx. (actually, whoever wrote the ''what does a compiler do'' thread should look at this as an example of an optimization)

Share this post


Link to post
Share on other sites
Back to the topic:

When I was learning pointers, the way I learned their uses was to imagine that if a function needed to "save" a value into one of the arguments, I had to use pointers.

Imagine this function: GetPlayerPosition(). Assuming it''s return value is bool (for success or failure), how do you return 2 values from this function? You can''t. But you CAN pass 2 pointers to 2 integers and then de-reference (de-pointer?) them to save their value into the arguments. So your function looks like this:

bool GetPlayerPosition(int* x, int* y)
{
//stuff
*x = player_x;
*y = player_y;
}

You just ''saved'' the value into the arguments themselves. References are just like pointers, only the compiler does all the de-referencing for you.

Does this make sense?

Share this post


Link to post
Share on other sites
quote:
Original post by kdogg
...


Well, yeah, that''s why there''s pretty much no reason to use inline assembly anymore. I was just playing around.

As for eax, aren''t ints 16-bit by default? I think you have to use unsigned long to get a 32-bit variable.

Share this post


Link to post
Share on other sites
As far as MSVC goes, check MSDN:

int, unsigned int - 4 bytes
long, unsigned long - 4 bytes


They''re the same thing, really. This is MS specific though, so YMMV with other compilers.

Share this post


Link to post
Share on other sites