Pointers...What is the point?
Moderator: Coders of Rage
- Big Grizzle
- Chaos Rift Cool Newbie
- Posts: 61
- Joined: Wed Sep 02, 2009 1:07 pm
- Current Project: 2d side scrolling shooter.
- Favorite Gaming Platforms: The SNES rules all!!! Super Aleste baby!
- Programming Language of Choice: Python
- Location: London, UK
- Contact:
Pointers...What is the point?
Firstly, sorry for the really bad subject title.
Anyway what I would like to know is what are pointers used for in C/C++. I just started learning C++ and I understand that they point to a memory address, but having only programmed in higher level languages I have no idea what they are primarily used for? What uses do they hold?
Now I am fairly sure some of the C++ whizzes on here are at this point thinking FACE PALM, but bear with me. I just need a simple example to ignite my imagination a little bit.
Anyway what I would like to know is what are pointers used for in C/C++. I just started learning C++ and I understand that they point to a memory address, but having only programmed in higher level languages I have no idea what they are primarily used for? What uses do they hold?
Now I am fairly sure some of the C++ whizzes on here are at this point thinking FACE PALM, but bear with me. I just need a simple example to ignite my imagination a little bit.
"Simplicity is the ultimate sophistication." - Leonardo da Vinci
http://caveofgrizzle.blogspot.com/
http://caveofgrizzle.blogspot.com/
Re: Pointers...What is the point?
Well firstly you can allocate memory dynamically with pointers, meaning instead of it all being on the stack in which it's all deleted when it goes out of scope, you can choose when it is allocated, and deallocated.
so with C++ memory allocation it'd be like:
A small note, just in case it isn't apparent to you; In this example, the pointer itself is on the stack, so when it goes out of scope, the POINTER is deallocated, not the memory it is pointing to. So if you only have one pointer pointing to something, and you don't deallocate the memory, when the pointer goes out of scope, you have just earned yourself a memory leak, meaning that memory was allocated, yet never deallocated.
so with C++ memory allocation it'd be like:
Code: Select all
someClass* myObjectOfSomeClass;
//Then we allocate the memory...
myObjectOfSomeClass = new someClass();
//then delete it when needed
delete myObjectOfSomeClass;
myObjectOfSomeClass = NULL;
/*I always set my pointers to NULL after I delete the memory, because the pointer is still pointing to that portion of memory, but what was there isn't there anymore, so you can get some funky results if you attempt to try any operations with it.*/
- Spikey
- Chaos Rift Cool Newbie
- Posts: 98
- Joined: Sat Dec 13, 2008 6:39 am
- Programming Language of Choice: C++
- Location: Ottawa, Canada
- Contact:
Re: Pointers...What is the point?
XianForce is correct. But there's also more! Since most of us programming games here, speed is an important issue. Passing pointers to a function is faster than passing objects, just imagine for a second: Your game character takes up 10000 bytes of memory while a (32 bit) pointer takes up 4 bytes. Obviously passing 4 bytes is going to be faster than passing 10000 bytes for each call.
Pointers still have more uses... Such as being used for linked lists or you can also do some funky stuff like pointers pointing to pointers
Pointers still have more uses... Such as being used for linked lists or you can also do some funky stuff like pointers pointing to pointers
- JaxDragon
- Chaos Rift Junior
- Posts: 395
- Joined: Mon Aug 04, 2008 2:03 pm
- Current Project: Kanoba Engine
- Favorite Gaming Platforms: PS3, PC
- Programming Language of Choice: C++
- Location: Northeast NC
Re: Pointers...What is the point?
What really made pointers useful for me, is the fact that with them you can modify the variable you are pointing to. For example, suppose you have a addition function that takes two numbers, adds them, and puts the result in a variable not defined inside the function. If you pass a normal variable to the function(as the result), you will have problems. Whereas if you use pointers, it should work flawlessly.
Re: Pointers...What is the point?
Yep, I think it's one of those things, where it's uses are only as big as your imagination type of things. There's a bunch of witty little ways you can use them to improve some aspect of something.Spikey wrote:But there's also more!
- programmerinprogress
- Chaos Rift Devotee
- Posts: 632
- Joined: Wed Oct 29, 2008 7:31 am
- Current Project: some crazy stuff, i'll tell soon :-)
- Favorite Gaming Platforms: PC
- Programming Language of Choice: C++!
- Location: The UK
- Contact:
Re: Pointers...What is the point?
Since everyone has already mentioned all of the usual uses for pointers (dynamic allocation, passing by reference instead of value) my justification is that they help implement a vital component of polymorphism.
When you want to define a generic interface for your classes, you will declare methods(member functions) in a class, but you will implement them in derived classes, in C++, derived classes have close relationships with their base types, and you can actually use a base pointer to hold the address of a derived type (but you can only use the functions which were declared in the base class), however, you are able to call the specific version of the method in the derived class, because polymorphism allows you to override the base class method and replace it with the derived class method.
This is useful if you needed to perform an operation on different classes, with the same function name, but each object has a different definition for that function, rather than calling each individual method, using wither local objects or by loads of different pointers, you can simply use a collection of base class pointers instead.
so for example, if I was implementing my own menu system, and it had lots of different controls, such as a textbox, some buttons, a label etc, in my solution i'm going to push them into a container within the menu object, the menu object needs to be able to handle the drawing and the updating of each control, without polymorphism and pointers, the menu would have to know exactly what controls need to be drawn and updated, but because of polymorphism and base class pointers, all you have to do is push base class pointers which contain addresses to the specific control into the container and let the menu class perform Draw() and Update() methods, for each control, a unique version of Draw() and Update() are called, thus making pointers incredibly useful
And i'm sure one of the pros on this forum will explain the usefulness of pointers to functions, although I must admit this is a grey area in my knowledge, and the guys on here have a lot more fun explaining them than me
When you want to define a generic interface for your classes, you will declare methods(member functions) in a class, but you will implement them in derived classes, in C++, derived classes have close relationships with their base types, and you can actually use a base pointer to hold the address of a derived type (but you can only use the functions which were declared in the base class), however, you are able to call the specific version of the method in the derived class, because polymorphism allows you to override the base class method and replace it with the derived class method.
This is useful if you needed to perform an operation on different classes, with the same function name, but each object has a different definition for that function, rather than calling each individual method, using wither local objects or by loads of different pointers, you can simply use a collection of base class pointers instead.
so for example, if I was implementing my own menu system, and it had lots of different controls, such as a textbox, some buttons, a label etc, in my solution i'm going to push them into a container within the menu object, the menu object needs to be able to handle the drawing and the updating of each control, without polymorphism and pointers, the menu would have to know exactly what controls need to be drawn and updated, but because of polymorphism and base class pointers, all you have to do is push base class pointers which contain addresses to the specific control into the container and let the menu class perform Draw() and Update() methods, for each control, a unique version of Draw() and Update() are called, thus making pointers incredibly useful
And i'm sure one of the pros on this forum will explain the usefulness of pointers to functions, although I must admit this is a grey area in my knowledge, and the guys on here have a lot more fun explaining them than me
---------------------------------------------------------------------------------------
I think I can program pretty well, it's my compiler that needs convincing!
---------------------------------------------------------------------------------------
And now a joke to lighten to mood :D
I wander what programming language anakin skywalker used to program C3-PO's AI back on tatooine? my guess is Jawa :P
I think I can program pretty well, it's my compiler that needs convincing!
---------------------------------------------------------------------------------------
And now a joke to lighten to mood :D
I wander what programming language anakin skywalker used to program C3-PO's AI back on tatooine? my guess is Jawa :P
- Big Grizzle
- Chaos Rift Cool Newbie
- Posts: 61
- Joined: Wed Sep 02, 2009 1:07 pm
- Current Project: 2d side scrolling shooter.
- Favorite Gaming Platforms: The SNES rules all!!! Super Aleste baby!
- Programming Language of Choice: Python
- Location: London, UK
- Contact:
Re: Pointers...What is the point?
Thanks for all of the helpful responses.
At this point my knowledge of C++ and memory management is lacking somewhat. I am too used to Python and it's built-in memory management. Hopefully through the preceding months my understanding will gradually increase. One eureka moment at a time.
At this point my knowledge of C++ and memory management is lacking somewhat. I am too used to Python and it's built-in memory management. Hopefully through the preceding months my understanding will gradually increase. One eureka moment at a time.
"Simplicity is the ultimate sophistication." - Leonardo da Vinci
http://caveofgrizzle.blogspot.com/
http://caveofgrizzle.blogspot.com/
- programmerinprogress
- Chaos Rift Devotee
- Posts: 632
- Joined: Wed Oct 29, 2008 7:31 am
- Current Project: some crazy stuff, i'll tell soon :-)
- Favorite Gaming Platforms: PC
- Programming Language of Choice: C++!
- Location: The UK
- Contact:
Re: Pointers...What is the point?
Indeed, that's what happened to me when I learnt pointers, I went from "pointers? yeah, I get what they are, but why would I use them" to "ooh, I could use a pointer for that, brilliant"
Good luck to you!
Good luck to you!
---------------------------------------------------------------------------------------
I think I can program pretty well, it's my compiler that needs convincing!
---------------------------------------------------------------------------------------
And now a joke to lighten to mood :D
I wander what programming language anakin skywalker used to program C3-PO's AI back on tatooine? my guess is Jawa :P
I think I can program pretty well, it's my compiler that needs convincing!
---------------------------------------------------------------------------------------
And now a joke to lighten to mood :D
I wander what programming language anakin skywalker used to program C3-PO's AI back on tatooine? my guess is Jawa :P
Re: Pointers...What is the point?
Meh, you'll catch on, I didn't get pointers when I first started either. :p
I'm an altogether bad-natured Cupid.
Re: Pointers...What is the point?
Yeah what everyone said above. I'll just chip in and agree that it does take a bit of time to understand pointers and their uses but eventually it will click.
Re: Pointers...What is the point?
Yeah, it took me a while to "get" pointers. The memory management stuff is a big pain in the arse.
A big reason is virtual functions:
Lets say that you're coding an RPG. In the RPG you have a character class, and inside it the virtual function Attack:
This is good, but what if you wanted the player to select an attack, and only the player, not NPCs? The answer is to use polymorphism, and therefore pointers. You can extend the attack function like this:
Ok, so now lets try it out:
The above code would NOT bring up the menu, because the Sonic Character is not a pointer. It would call the base Attack function defined in Character.
You'd have to do this:
And another reason - you will always get a handle to the same object with pointers. Every time you pass a class that isn't a pointer to a function, you'll just create a new object. For example:
That would not change the x and y values of the object that you pass to the function, it would just create a new object and change that. So you have to pass it the address of the variable, AKA a pointer.
These are just the reasons why I use them. There's loads more...
A big reason is virtual functions:
Lets say that you're coding an RPG. In the RPG you have a character class, and inside it the virtual function Attack:
Code: Select all
class Character
{
public:
//usual stuff like constructors etc here
virtual void Attack(Character target)
{
//choose an attack automatically
}
};
Code: Select all
class Player
{
void Attack(Character target)
{
//bring up a menu of attacks
}
}
Code: Select all
Player Sonic;
Character Mario;
Sonic.Attack(Mario);
You'd have to do this:
Code: Select all
Player* Sonic = new Player();
Character* Mario = new Character();
Sonic->Attack(Mario);
//cleanup, further down somewhere in your code when the objects aren't needed
delete [] Sonic;
delete [] Mario;
Code: Select all
void SetObjectPos(Object obj, int x, int y)
{
obj.x = x;
obj.y = y;
}
These are just the reasons why I use them. There's loads more...
All programmers are playwrights and all computers are lousy actors.
- Spikey
- Chaos Rift Cool Newbie
- Posts: 98
- Joined: Sat Dec 13, 2008 6:39 am
- Programming Language of Choice: C++
- Location: Ottawa, Canada
- Contact:
Re: Pointers...What is the point?
There's an exploit here. Drop the []'s, delete [] is trying to delete an array of objects while you did not allocate an array. Resulting behaviors may be unnoticeable but should be avoided. http://taossa.com/index.php/2007/01/03/ ... lete-in-c/Code: Select all
Player* Sonic = new Player(); Character* Mario = new Character(); Sonic->Attack(Mario); //cleanup, further down somewhere in your code when the objects aren't needed delete [] Sonic; delete [] Mario;
Re: Pointers...What is the point?
Oops ^^Spikey wrote:There's an exploit here. Drop the []'s, delete [] is trying to delete an array while you did not allocate one. Resulting behaviors may be unnoticeable but should be avoided. http://taossa.com/index.php/2007/01/03/ ... lete-in-c/Code: Select all
Player* Sonic = new Player(); Character* Mario = new Character(); Sonic->Attack(Mario); //cleanup, further down somewhere in your code when the objects aren't needed delete [] Sonic; delete [] Mario;
I agree with you 100%, thanks for correcting me. I was working with some char* arrays just before answering that post, I guess I've been working on them for too long
All programmers are playwrights and all computers are lousy actors.
- captjack
- Chaos Rift Cool Newbie
- Posts: 50
- Joined: Fri Sep 18, 2009 4:23 pm
- Current Project: engine framework
- Favorite Gaming Platforms: PC, XBox 360, PS3
- Programming Language of Choice: C, C++
- Location: Northern Virginia
Re: Pointers...What is the point?
Oh, you tricksy devil!Spikey wrote:... funky stuff like pointers pointing to pointers
Code: Select all
int (*(*kill_me_now)(char *,double))[9][20]
Code: Select all
int *(*crappage())();
<curls in corner, sucking thumb> No... make it stop!
-capt jack
- MarauderIIC
- Respected Programmer
- Posts: 3406
- Joined: Sat Jul 10, 2004 3:05 pm
- Location: Maryland, USA
Re: Pointers...What is the point?
On the topic of pointers that are (initially) confusing,
mytype* const mypointer
const mytype* mypointer
const mytype* const mypointer
Hooray! Const correctness!
mytype* const mypointer
const mytype* mypointer
const mytype* const mypointer
Hooray! Const correctness!
I realized the moment I fell into the fissure that the book would not be destroyed as I had planned.