Pointers? another stupid question.....

Started by
8 comments, last by Waxy 17 years, 7 months ago
i'm a VB guy who's very much a C noobie. (actualy, i'm starting with VC++.net 2003) I've read about pointers and understand their basic varable use through memory locations. but what i fail to understand is when they could prove to be usefull instead of using a normal varable. can someone explain to me the actual usefulness of pointers? (i'm sure there must be a good use for them because i see them all over the place in C++ source codes) to elaborate: ------------------------------------------------------------- // my first pointer #include <iostream> using namespace std; int main () { int firstvalue, secondvalue; int * mypointer; mypointer = &firstvalue //point to this varable *mypointer = 10; //make my target = 10 mypointer = &secondvalue //point to second varable *mypointer = 20; //make my target = 20 cout << "firstvalue is " << firstvalue << endl; cout << "secondvalue is " << secondvalue << endl; return 0; } ----------------------------------------- why not just say: ------------------------------------------ // my first pointer #include <iostream> using namespace std; int main () { int firstvalue, secondvalue; firstvalue = 10; secondvalue = 20; cout << "firstvalue is " << firstvalue << endl; cout << "secondvalue is " << secondvalue << endl; return 0; } ---------------------------------------------- This may be a poor example i have been shown but it is much simpler and saves the trouble of creating and handling a pointer. In the example i was given a pointer is more of a hinderance than a benifit. so can someone clarify to the the advantages of pointers?
Advertisement
class Soldier {public:  Soldier () : target(0), health(100) {}  Soldier* target;  int health;  Attack() { if (target) target->health -= 1; }};Soldier a, b;a.target = &ba.Attack();std::cout << b.health << std::endl;


Can you achieve the functionality above without pointers?

If you have learned about the new and delete operators, you can dynamically allocate memory as needed instead of having to pre-allocate every peice of memory that you caould possibly have.
Heres an example:
poop = playern[dump-1]->ctynum(type); // retrieve # of farms player has
citykin = buildnum(poop); //adds 1 to # of total farms/saves to citykin
x = xcoord(); //gets x coordinate
y = ycoord(); // gets y coordinate
pn = playern[dump-1]->getpnum(); //stores player# as pn
ri = playern[dump-1]->getri(); // stores player race as ri
playern[dump-1]->ctycntinc(2); //increment # of building type being built
farm* f; // define farm pointer
f = new farm; // allocate memory for farm and assing addy to f
f->farmcreate(pn, ri, citykin, x, y); use pointer to construct farm
playern[dump-1]->addfarmpnt(f); //save * to array position in player class
f->farmdisplay(); system("pause"); //display info on farm
Without pointers I would be forced to define every object that the user could possibly create. Also, I would be forced to save copies of massive objects in many many places.
you need pointers for call by reference and dynamic memory management
Quote:Original post by flery
you need pointers for call by reference


Actually, for this, you only need references.
Yes, I agree with you that your example is very dumb.
It's a classic textbook example, which tries to illustrate how concepts work, but is totally useless.

Here's some examples of why pointers are required:

1. Dynamic memory allocations. If you don't know at programming time how many objects your application needs, you can declare them. Instead, you allocate them at runtime. Consider a game, and the player fires a new bullet. You need an object to represent it (position, speed, etc.). You would probably write this piece of code:

Bullet* bullet = new Bullet();

bullet is a pointer to the newly created bullet object. Now how do you keep references to an unknown number of objects ? By using data structures like linked lists, vectors, hash tables, binary trees, or whatever suits your requirements.
If you study data structures (which you really should), you'll discover that those are using pointers all over the place. And you can't avoid them like you could in your 'textbook' example.

Another example requiring dynamic memory allocation could be a mesh loader. You don't know how many vertices/faces your mesh contains before actually loading it -> you need dynamic memory allocation -> you need pointers.

2. Pointers can be more performant than static variables, especially when considering large structures. Let's say you have a function which Inverts a 200x200 matrix:

Invert200(Matrix m)

If you pass the matrix by value, at runtime you're copying 40'000 elements (maybe doubles) on the stack. Quite a performance hit.

If you pass it as a pointer, or by reference (which is a disguised pointer):
Invert200(Matrix* m) or
Invert200(Matrix& m)
then you are only copying a pointer (4 bytes, maybe 8 on 64 bits cpu) on the stack. A huge difference.

3. One usually likes to use pointers to do buffer manipulations. True, you can replace this with an array and an index, but sometimes it's simpler to use pointer arithmetic directly. And anyway, in C an array is just another disguised pointer.

4. Pointers to functions can be use to provide genericity. But this is a little bit different than your basic "data" pointer, and one could argue that it would be better designed by using inheritance and virtual functions, so I won't go deeper into this.

Have a nice day,
jods
Quote:Original post by ToohrVyk
Quote:Original post by flery
you need pointers for call by reference


Actually, for this, you only need references.

As jods implied, references are really just syntactic sugar for pointers. If you look at how the code works at the assembly level, it's the 32-bit pointer being passed to your pass-by-reference function.
I looked at that for a good five minuites switching
between the toutorial pages of the sites i have open.
i haven't reached classes or functions yet so bear
with me if i'm way off here, but...


it looks like you're trying to say that with pointers
you can do something kinda like :

a's target becomes b's health so that when a.target is
subtracted you're actualy subtracting from b's .health
without changing a's .target - which stays b's .health?








Quote:Original post by drakostar
As jods implied, references are really just syntactic sugar for pointers. If you look at how the code works at the assembly level, it's the 32-bit pointer being pushed onto the stack for your pass-by-reference function.


This is incorrect. The pointers and references in C++ are usually implemented in the final executable using memory addresses; references are not implemented using pointers, since pointers themselves do not exist anymore at the binary level either (and besides, there's nothing about pointers that references would use that isn't already available in memory addresses).

Aside from the fact that they share the same implementation in a certain set of situations, there is a world of difference between them. References cannot be re-seated, which makes static analysis and optimization much easier (as far as leaving a variable in a register, which is not possible if it is directly addressed). Passing literals or temporary values by reference is something that pointers cannot do, but references can. And, of course, there's the entire set of compiler-enforced limitations on top of references that differs from the compiler-enforced pointer arithmetics.

Now, if you were saying that "You need memory addressing to pass by reference," then I would agree, and add "Yes, in the form of references, possibly constant ones."

Evil poptart - sorry, all greek piglatin to me
Flery - sounds familure.... i'll brain storm on it a bit.
ToonhrVyk - i know what you said but it was about what poptart was talking about and so it's not much help. :D

JODS! - i love your examples!
#1. - memory allocation: if you speak VB then tell me, is that using REDIM X(I+1) ? it sounds alot like it.
#2. - so it's like building a mesh of a man then refering to it 100 times as you draw it instead of copying it to 100 players then drawing it.... :/ not sure i got you 100% on that one but if i do then it makes sense for processor load.
#3 - buffers- don't think i'm there yet.
#4 - thank you for not going deeper. i fliped foward a little big, saw pointer functions (like ToohrVyk's soldier attack example?) and know i'm not ready for that yet.



ToohrVyk - you're explaining einstein's theory to an acorn. not your fault, blame the acorn for being to lazy to try growing into a tree before today.



Thanks, guys, for your feedback. you've shown me that pointers and refrences
provide a flexibility i have not yet seen in the demonstrations and sample
codes. with Jobs memory allocation and the reference to pointer functions
i say that right?) i beleive i see one example of pointer's flexibility for
uses.

i'll hang in there and keep banging away. :D

This topic is closed to new replies.

Advertisement