Sign in to follow this  

do i have a use for pointers?

This topic is 4400 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Okay, my question is this. What do I need pointers for? I have a program now (and several ive made before) and i've never used a pointer once. Basically I found them over complicated when i could just pass in a value instead of a pointer to a value. I heard they save space because the function the pointer is passed to doesn't need to duplicate the whole variable so i decided it'd be in good form to start using them. But when and where do i use them? I've not found a place. Basically I have a function right now that is in a class called CButton. It's a function that checks the state of the button and then sets a integer called state within the function to a different number depending if the mouse is clicking, hovering or not on a button. I know for other functions (ie. my SetButton function) i dont need pointers cuz the values go like so. void SetButton(char name[], int x, int y, int r, int g, int b); and for each one i give a constant value like this button_new.SetButton("New Map", 10, 10, 150, 90, 90); but for my function CheckState, do i use pointers? should i declare it like this CheckState(int x, int y, bool click); or with pointers like this CheckState(int *x, int *y, bool click); or is using pointers for small variables and data like that just gonna get mucky and over complicated? Is using them for integers really saving as much space as i've read to be true? Or should I use pointers for functions that use bigger data types...like bitmaps? ie: void DrawBitmap(BITMAP *bm); Even then i'm not sure i should, cuz in my other program i have functions i pass bitmaps to and it's not slowed down or anything because of that. Help please.

Share this post


Link to post
Share on other sites
Later on in game programming when you have to "pass" an entire surface to a function, instead of creating an entire copy of it the function edits the one passed to it which potentially saves a huge ammount of memory (which you already knew). So another case where you would be required to use a pointer is if you want the function to edit the variable instead of just editing the temporary variable created for the called function. Hope that makes sense to you, ask me to clarify if it doesn't.

EDIT: An example

#include <iostream>
using namespace std;

void SomeFunction(int Var1);

int main()
{
int Var1 = 3;
cout << Var1 << endl; // What will this print?
SomeFunction(Var1);
cout << Var1 << endl; // And what will this print?
return 0;
};

void SomeFunction(int Var1)
{
Var1 = 5; // Edit the value
return;
};


Now using pointers make SomeFunction change Var1 in main to 5.

Share this post


Link to post
Share on other sites
in windows or sdl or any higher level programming pointers are absolutley needed.. i once thought exactly what you did but you jump into sdl or windows api and ull quickley learn how much they are needed.. the only time you should really use them is if your wanting to edit it... now like this..

void timestwo(int x)
{
x = x * 2;
}

x dies and nothing happens but if you do

void timestwo(int *x)
{
&x = &x * 2;
}


not sure about syntax.. but there youve just directly edited the data in the pointer... hope this helped you

Share this post


Link to post
Share on other sites
Use references where you can, pointers where you have to (note that this covers C as well, since you "have to" use pointers for all reference uses there). You want to pass a reference or pointer to a function when:

a) the thing being passed is large enough to benefit - as a rule of thumb, use it for structs and classes, and pass primitive types by value. (Use a const reference in this case, unless (b) also applies.)
b) you want the function to change the parameter and for the change to be "seen" by the calling code. (BUT you should first consider if you can just use the return value instead.)

Now then:

- Please don't put that C in front of your class names. Similarly, don't add 'Button' to the names of Button member functions. Neither of these adds useful information for either you or the compiler.

- Use std::string for text data. It will save you headaches in the long run.

- Since this class represents a "button" of some sort, check that your API doesn't already provide something similar.

Share this post


Link to post
Share on other sites
Jembulura: The first part about passing a whole surface and saving memory etc. makes sense but the second part about passing a pointer to edit a variable outside the function instead of the temporary one created doesn't. Why not just return the new value and set the variable that way?

Also, should I use pointers for my CheckState function or what that be too much of a hassle for the small amount of space it saves, besides i'm not aiming to change the mouse's position; just to read it.

Share this post


Link to post
Share on other sites
for preformance sake really... and energy sake for you.. lol why add all the time into adding more lines of code.. take memory up because its editing a deplicate.. send it back and the memory still is wasted... when you can use once chunk of memory and keep it simple?

Share this post


Link to post
Share on other sites
if the your classses are potentially large( contains a std::vector, or some cynamic array ), then you shouldnt pass by value. this means passing using pointers, which is syntactically difficult, or refernces, which are easier on everyone.


//so instead of

void SomeFunction( PotentiallyLargeType value );

//we could use

void SomeFunction( PotentiallyLargeType& reference );
//or
void SomeFunction( const PotentiallyLargeType& reference );



the const means that you promise the compiler you wont change the object, just inspect it...

pointers do the same thing as references but are more difficult, but they can do more.

Share this post


Link to post
Share on other sites
About the only place I can think of were you absolutely need to use a pointer is dynamic memory allocation.

That of course begs the question as to when you would use a reference. A few have already been mentioned, polymorphism would be the biggest one.

Share this post


Link to post
Share on other sites
Quote:
Original post by Le_Danse_Macabre
Jembulura: The first part about passing a whole surface and saving memory etc. makes sense but the second part about passing a pointer to edit a variable outside the function instead of the temporary one created doesn't. Why not just return the new value and set the variable that way?

Also, should I use pointers for my CheckState function or what that be too much of a hassle for the small amount of space it saves, besides i'm not aiming to change the mouse's position; just to read it.


pointers can be used to "return" several values at once.

e.g.

void whereIsMouse( int& x, int& y );

if the time taken to copy an int is the slowdown in your program you are not doing too bad at all...

checkState should return the state. its the easiest on everyone, i think

Share this post


Link to post
Share on other sites
I think i've got it, thanks everyone. Now just for my own satisfaction, i believe this is what i do with the source posted by Jemburula.


#include <iostream>
using namespace std;

void SomeFunction(int *Var1);

int main()
{
int Var1 = 3;
cout << Var1 << endl; // What will this print?
SomeFunction(*Var1);
cout << Var1 << endl; // And what will this print?
return 0;
};

void SomeFunction(int *Var1)
{
&Var1 = 5; // Edit the value
return;
};

Share this post


Link to post
Share on other sites
Quote:
Original post by Le_Danse_Macabre
the second part about passing a pointer to edit a variable outside the function instead of the temporary one created doesn't. Why not just return the new value and set the variable that way?


Hey,

If you're wanting to pass back several values, there's no current way to do it outside of creating your own structure to return them, or using a boost? tuple, which _will_ eventually become part of the language the way things are going.

But references/pointers are incredibly handy for the following situations:
int GetMousePos(int* x, int* y)

where you want the user to specify either null [0] or an int which receives the mouse x and y pos. Actually defining and copying from a custom structure here is commonly used, but kind of silly IMO, as this is more straightforward, logical and lightweight.

However, if you didn't want to allow null parameters, and want the function to return two values, both of which are important, use references.
int GetMousePos(int& x, int& y)

Everyone [lots of programmers] make a big kerfuffle about pointers and ignore references, but references generally lead to better, cleaner code, because you are guaranteed to be able to view and edit the variables passed, and the compiler won't allow you to do many silly things with references.

Hope this helps,

CJM

Share this post


Link to post
Share on other sites
sorry, just interchange the * and the &


#include <iostream>
using namespace std;

void SomeFunction(int *Var1);

int main()
{
int Var1 = 3;
cout << Var1 << endl; // What will this print?
SomeFunction(&Var1); // change
cout << Var1 << endl; // And what will this print?
return 0;
};

void SomeFunction(int *Var1)
{
*Var1 = 5; // change
return;
};

Share this post


Link to post
Share on other sites
Quote:
Original post by Le_Danse_Macabre
I think i've got it, thanks everyone. Now just for my own satisfaction, i believe this is what i do with the source posted by Jemburula.

*** Source Snippet Removed ***


Ignoring the incorrect syntax..

No. There's no reason to use a pointer over a reference here.


void SomeFunction(int& Var1)
{
Var1 = 5; // Edit the value
};

Share this post


Link to post
Share on other sites
e.e; sorry everybody, just a few more questions.


* = the value of the variable the pointer is pointing to.

& = the address of the variable the pointer is pointing to.

That's right, right?

And a thing about my CheckState function. I'm not using the function to obtain the values of the mouse x/y or to return them, in fact i'm just using it to check them. like so:

void CButton::CheckState(volatile int *mx, volatile int *my, bool clicking)
{
if((*mx > x) && (*mx < x+50))
{
if((*my > y) && (*my < y+15))
{
if(clicking)
state = 2; // clicked
if(!clicking)
state = 1; //hovering
}
}

state = 0; //doing nothing
}



Should I be using pointers for that or is it just a waste of time? Also, is my syntax correct?


Zahlman : Thanks for the tips, I just add C before my classes due to force of habit because this was the way the tutorials did it. Also, allegro does have GUI functions for buttons but they're ugly as hell so i made my own.

Share this post


Link to post
Share on other sites
Quote:
Original post by Le_Danse_Macabre
e.e; sorry everybody, just a few more questions.


* = the value of the variable the pointer is pointing to.

& = the address of the variable the pointer is pointing to.

That's right, right?

And a thing about my CheckState function. I'm not using the function to obtain the values of the mouse x/y or to return them, in fact i'm just using it to check them. like so:

void CButton::CheckState(volatile int *mx, volatile int *my, bool clicking)
{
if((*mx > x) && (*mx < x+50))
{
if((*my > y) && (*my < y+15))
{
if(clicking)
state = 2; // clicked
if(!clicking)
state = 1; //hovering
}
}

state = 0; //doing nothing
}



Should I be using pointers for that or is it just a waste of time? Also, is my syntax correct?


Zahlman : Thanks for the tips, I just add C before my classes due to force of habit because this was the way the tutorials did it. Also, allegro does have GUI functions for buttons but they're ugly as hell so i made my own.


this is a prime example of when not to use pointers at all. the only thing youve done here is kill efficency... why the volatile modifier? it forces the compiler to reload the value from system memory every access, without any need.

also, as you are not modifing the values there is no point. just use

void CButton::CheckState(int mx, int my, bool clicking)

and also use an enum:
button.h

class Button
{
private:
enum States
{
NOTHING,
HOVERING, // or HAS_FOCUS
CLICKING,
};
State state;
public:
/*
...
*/

};


its clearer to everyone...

Share this post


Link to post
Share on other sites
Thanks.

I used the volatile modifier because allegro uses it when to store it's mouse x and y...i just did it because of that, i've actually never seen or heard of the volatile modifier...I should just type cast then as a normal integer? Also, could you explain what a volatile int does?

Share this post


Link to post
Share on other sites
Quote:
Original post by Le_Danse_Macabre
Thanks.

I used the volatile modifier because allegro uses it when to store it's mouse x and y...i just did it because of that, i've actually never seen or heard of the volatile modifier...I should just type cast then as a normal integer? Also, could you explain what a volatile int does?


volatile tells the compiler that you dont reeally own the variable. a volatile int is an int that could change at any time. the compiler assumes all other variables are owned by it and it can do whatever it wants with them, like stick them in a register for the duration of a function. because the compiler can no longer gaurentee that the value wont change without it knowing, it has to check the value before it uses it. every time. thats not as fast as it could be...

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Quote:
Original post by Zahlman
....
- Please don't put that C in front of your class names. Similarly, don't add 'Button' to the names of Button member functions. Neither of these adds useful information for either you or the compiler.
...
But it does add useful information to me and anybody else who uses it, if you follow the common rule that a C prefix indicates a [u]concrete[/u] class. Then it's easy to tell an interface from its implementation.


Pointers are needed as, someone said, with polymorphism. Classic example:
[CODE]
#include

// Interface class, dictates how concrete classes should be handled
// This class can't be instantiated on its own
class IAnimal
{
public:
virtual void Speak() = 0;
};

// Concrete specification of an IAnimal type
class CDog:
public IAnimal
{
public:
void Speak() { std::cout Speak();
animal2->Speak();

return 0;
}
[CODE]

Share this post


Link to post
Share on other sites
Quote:
Original post by Anonymous Poster
Pointers are needed as, someone said, with polymorphism. Classic example:


references can be used to gain polymorphic behaviour( and its source, not code for future reference )




class Shape
{
public:
virtual void draw() = 0;
};

class Circle : public Shape
{
public:
virtual void draw(){ cout << "Circle!\n"; }
};


class Square : public Shape
{
public:
virtual void draw(){ cout << "Square!\n"; }
};

void drawShape( Shape& theShape )
{
theShape.draw();
}

int main()
{
Circle c;
Square s;
drawShape(c);
drawShape(s);
return 0;
}



Share this post


Link to post
Share on other sites
i still have to see a use for pointers where a reference cant do the same thing, and just because we had a somehow similar discussion about pointers/references on irc a while ago i will post a little code snipped, where most of 'us' would use pointers (dynamically allocating memory)...


char& stuff= *new char[12];
memcpy(&stuff, "Hello World\0", 12);
std::cout << &stuff << std::endl;
delete[] &stuff;

so pointers must die...


T2k

Share this post


Link to post
Share on other sites
Quote:
Original post by Anonymous Poster
But it does add useful information to me and anybody else who uses it, if you follow the common rule that a C prefix indicates a [u]concrete[/u] class. Then it's easy to tell an interface from its implementation.


True, that information can be useful in some cases. However, I have always found the Java way more elegant: interfaces which are explicitely meant to be implemented by an user-defined class end in 'able'. For instance: Runnable, Serializable ...

Share this post


Link to post
Share on other sites
I'll add my 2cents into this. I don't use that many pointers in my code. I use them mainly for dynamic memory allocation(the only way to do that) and for modifying things inside of functions so I don't have to do it myself after returning from the function. For example. I have a struct that contains information for a sound effect/music stream(be OpenAL or DSound) and I have a class that controls loading and playing of these sounds, as well as positioning of the listener and sounds in 3d space. Instead of making the struct load itself, I use a pointer to pass the struct into the class that then loads the file and gives the information to the struct. I think this could be done with references, but I think it is easy the way I do it. Besides that, I don't have much use for pointers yet. Another use that isn't as common is for temporary pointers to a part of an array. For example either a 3d model format or an image format. You use pointers to point to each section of the file and can change it to point to individual structures within the file.

Share this post


Link to post
Share on other sites
Quote:
Original post by T2k
i still have to see a use for pointers where a reference cant do the same thing, and just because we had a somehow similar discussion about pointers/references on irc a while ago i will post a little code snipped, where most of 'us' would use pointers (dynamically allocating memory)...


char& stuff= *new char[12];
memcpy(&stuff, "Hello World\0", 12);
std::cout << &stuff << std::endl;
delete[] &stuff;

so pointers must die...


T2k

Yuck. Do you honestly believe that to be equivilent to using a point to char? It has all the problems of raw memory management, with none of the syntactic benefits that a char* would provide.

CM

Share this post


Link to post
Share on other sites
Quote:
Original post by Conner McCloud
Quote:
Original post by T2k
<Stuff>

Yuck.

Quoted for emphasis (this particular case - std::string, more generally - a standard sequence container). Also non-idiomatic even for special cases.
Quote:
Original post by T2k
i still have to see a use for pointers where a reference cant do the same thing.

A reference can't be reseated and can't be null (no, char & c = *static_cast< char * >(0); does not create a null reference, it is undefined behaviour).

Enigma

Share this post


Link to post
Share on other sites
Quote:
Original post by Enigma
A reference can't be reseated and can't be null (no, char & c = *static_cast< char * >(0); does not create a null reference, it is undefined behaviour).


I just realized how silly it is to say that a reference is created by dereferencing a pointer.

Share this post


Link to post
Share on other sites
Sign in to follow this