It is currently Tue May 21, 2013 9:14 pm Advanced search

C++ Pointers

Non-project-specific matters-- talk about art, music, writing, coding and the creative process.

C++ Pointers

Postby Valeour » Sun Jul 24, 2011 12:20 am

Okay, does anybody have a simplified explanation of Pointers? I've used them before, and I know how to use them in some cases, but I don't really understand what they are. I've had information thrown and me, but it's more 'in-one-ear-and-out-the-other'.

All I know is that;
Pointers are a kind of dynamic memory and point to addresses.
...and that's it really, why are they so useful, and when should you use them?
User avatar
Valeour
 

Re: C++ Pointers

Postby mcc » Sun Jul 24, 2011 1:01 am

This is a really deep question, it is sort of like you are asking "how do you use C++"?

Pointers are just variables containing memory addresses.

If you dereference a pointer, C++ will go to that address in memory and a act as if that piece of memory is a variable of the pointer's type. So like if
Code: Select all
int *ptr = 543;
then saying
Code: Select all
*ptr
means "look at the integer stored at memory address 543" (note: for several reasons, never assign a number directly to a pointer like this).

You use pointers for the same purposes you use "references" in java or javascript or C#. If you dynamically allocated some kind of object, then you need to use a pointer to keep track of where it is.

Almost any use of pointers other than this one is sort of an "advanced" usage that you probably shouldn't worry about yet. For example it is possible to use pointers to surf around memory and "interpret" raw data in memory as different kinds of structures or values, but you should not do this unless you know exactly what you are doing.

Maybe it would be easier if you read up on a guide on pointers in C/C++ online, and told us if there is anything you do not understand.
User avatar
mcc
 

Re: C++ Pointers

Postby Nexidian » Sun Jul 24, 2011 1:04 am

You may want to check out these two links:

This one discusses dynamic memory allocation in c++ whilst briefly mentioning pointers
http://wibit.net/curriculum/the_c_linea ... #lesson-81

And this one discusses pointers in C, which i imagine would be almost similar to C++
http://wibit.net/curriculum/the_c_linea ... #lesson-45


-Nexy
User avatar
Nexidian
 
Location: England

Re: C++ Pointers

Postby Valeour » Sun Jul 24, 2011 1:08 am

Oh no no, don't get me wrong, I know how to use them and what they do, but I mean like;

Why use them? I mean, what's the difference between & reference, and a pointer? They effecitvely do the same thing to me, except pointers point to an address unless deref'd as mentioned, but references just seem a bit cleaner?

And even then, why not just use int myvar;? What benefits does dynamically allocating memory have? I really don't see a difference between making a pointer to a heap, or just making a new int.

Edit:
Forgot to mention, I know why you reference through a function, because you don't 'copy' the value and it's easier to kind of 'reference' it, but other than that, I dunno.
User avatar
Valeour
 

Re: C++ Pointers

Postby nyarla » Sun Jul 24, 2011 1:29 am

Valeour wrote:And even then, why not just use int myvar;? What benefits does dynamically allocating memory have? I really don't see a difference between making a pointer to a heap, or just making a new int.


Depends what you're doing.. if you're generating a lot of data but you don't know how much until runtime (eg a procedurally generated game map which can be different sizes), dynamically allocating the memory could make the code feel more elegant... I'm not super experienced but from what I can tell, whether this is a good idea or not basically just comes down to finding a balance between memory use and speed.

Like, you could allocate enough memory for <maximum map size>, and then just use however much of it you need - possibly "wasting" some memory. A single allocation at load time...nice and fast. Or you could dynamically allocate it as needed, which may end up being a bit slower (memory fragmentation? I don't know much about this but have heard of it...), but possibly also use up less memory.

This stuff starts to matter a bit when coding for less powerful hardware like phones :)

I went all dynamic allocation style, but now I'm tending back towards everything allocated at load time.. less hassles in the end, and yeah, a bit faster on low end hardware...
User avatar
nyarla
 
Location: melbourne

Re: C++ Pointers

Postby mcc » Sun Jul 24, 2011 1:40 am

Valeour wrote:Why use them? I mean, what's the difference between & reference, and a pointer? They effecitvely do the same thing to me, except pointers point to an address unless deref'd as mentioned, but references just seem a bit cleaner?


References are pointers, but a bit cleaner. I think you should use references instead of pointers absolutely whenever you can.

There is only one time you cannot use references and have to use pointers: References cannot be reassigned. If you say int &b = a; then "b" is pointing to "a", forever and always. You cannot point it to "c" later. If you must have a variable which is pointing to one thing at one point, but will be pointing to another thing later on, you should use a pointer. If you can't think of a reason why you would do this, then this is a sign you should be using references.

And even then, why not just use int myvar;? What benefits does dynamically allocating memory have? I really don't see a difference between making a pointer to a heap, or just making a new int.


Sometimes you need to allocate a number of things, but you do not know how many things you will need until the program is running. If you need four Enemy objects, you can say Enemy a,b,c,d; or Enemy enemylist[4];. But what if you need somewhere between four and four million Enemy objects, and exactly how many will depend on what happens mid-game? Then you will have to dynamically allocate the Enemy objects once you know you need them.

Sometimes you have something which is very large, but which you might not ever need. Like maybe there is an image which is the background for your Preferences pane, and it takes up a megabyte of memory, but it is never shown unless you open the Preferences pane. It could be wasteful to allocate this statically, because maybe you will never need it. It would make more sense to wait until the Preferences pane is opened the first time, and then dynamically allocate it then.

You can maybe avoid even these two cases if you are using the STL (although the STL will be using pointers internally...).
User avatar
mcc
 

Re: C++ Pointers

Postby Nexidian » Sun Jul 24, 2011 1:46 am

Even though this is not my post, thank you nyarla and mcc, you both cleared up my problem with pointers too :)
Very well explained thank you

-Nexy
User avatar
Nexidian
 
Location: England

Re: C++ Pointers

Postby Jack Sanders » Sun Jul 24, 2011 2:28 am

Think about it this way!

A pointer is like a sticky note telling you where something is. It isn't the thing itself, you just have written on it where the thing is.

You can easily create another sticky note and give the location of the same exact object. They both tell you where that object is, but they themselves aren't it.

If you destroyed the sticky note, the object won't be destroyed. You just don't know how to find it anymore.
(note: I wasn't using the programmatic term for object. Just an object by it's dictionary meaning)

In practice:
Code: Select all
string* BobsName = new string("Bob");

(note: not sure if that's a valid constructor. I assume it is.)

So, when you define <string* BobsName> you're creating the sticky note. The "=" is you writing a description of how to get an object on the sticky note. <new string("Bob");> is creating the object itself, which is independent of the sticky note.

Pointers main use is just in how your organize and distribute data across your system. With pointers, you can avoid data duplication where it isn't needed. Very nice things can be done by manipulating the properties of pointers(Which I touched on above) which form the foundation of how a LOT of things are done in C++.

Hope my analogies helped. :)
God speed!
User avatar
Jack Sanders
 
Location: California, USA

Re: C++ Pointers

Postby Valeour » Sun Jul 24, 2011 9:58 am

Okay starting to get the idea now, i guess the best practice now is to actually program with them. Thanks guys. :)
User avatar
Valeour
 

Re: C++ Pointers

Postby Isaac » Sun Jul 24, 2011 5:53 pm

I haven't read this thread word-for-word, so I may be simply repeating what someone else has said, but it never hurts to reiterate.

In C, you don't have references. You just have pointers, so C code does use pointers as a way of passing arguments "by reference" so that you can change the values of the arguments in the function itself, as in the very common swap() example:

Code: Select all
void swap(int* a, int* b) {
     int temp = *a;
     *a = *b;
     *b = temp;
}

C++ introduced references, which do away with the need of having all the asterisks in code like this.

Code: Select all
void swap(int& a, int& b) {
     int temp = a;
     a = b;
     b = temp;
}

Much cleaner. So in C++, references and pointers now serve two distinct purposes. You can use pointers the C way for passing arguments by reference, but that's doing it the C way, not the C++ way. There are many, many situations where using pointers is necessary, however. Pointers are how you manage values that are stored in the heap, instead of the stack. When you create an object in C++ (a regular old object, not a pointer), like so

Code: Select all
MyObject object("hi");

it is allocated on the stack, and it is removed completely from memory when the block of code it was in ends (when it hits a "}"). Dynamically allocated values don't live by those rules. For example, making an object like this:

Code: Select all
MyObject* object = new MyObject("hi");

Will allocate it on the heap (which is just a fancy word for how the runtime keeps track of the memory that your program owns). They will stay around as long as you want them to.

It's hard to describe how this is useful if you haven't encountered the need before, but perhaps the most trivial and powerful example is a linked list. Take a look at Wikipedia's linked list article and notice that pointers play a core role in making them work.

Another example: C++'s vector STL data-type isn't a linked list, but an array of dynamically allocated memory. Arrays have a fixed size. When you pump more values into an STL vector than its array can hold, the STL dynamically allocates a new array, and copies all the values from the old array into the new one. The only way this dynamically allocated array can be kept track of and used is via a pointer to tell the STL where it is so that it can be manipulated.
User avatar
Isaac
 

Re: C++ Pointers

Postby Draknek » Sun Jul 24, 2011 6:09 pm

I've seen this video posted a few times in the past for "help confused by pointers" posts.
User avatar
Draknek
 
Location: Coventry, UK


Return to Process

Who is online

Users browsing this forum: No registered users and 1 guest

cron