Archived

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

jedis1000

Pointers?

Recommended Posts

jedis1000    122
I know what a pointer is... well at least I think that I do. My definition of a pointer would be a variable that "points" to another variable in the memory. This address is then stored in that pointer''s variable. The pointer says, "Hey look! There is a variable in this section of the memory. Here is where it is stored: -x--------! Wowee! My question to you people is, Why do you need to use pointers? People usually don''t need to see where their variables are stored, so why even use them at all? Can you cange a value in a varaible according to where is it located in the computers memory? Is there a specific purpose that I''m missing here? Please, fill me in on this one!

Share this post


Link to post
Share on other sites
Palidine    1315
you use pointers when you want to use dynamic memory. for instance you can''t have a linked list or any other kind of dynamic memory structure without pointers. you can think of a linked list as a list of objects or variables that is variable in size. an array is fixed in size, but a linked list can grow or shrink depending on how many items you want in it.

you can also use pointers to access memory on the heap. your machine divides memory between stack and heap. stack is where the memory goes when you declare:

int foo;

the stack is fixed in size (typically 1-2MB per application). the heap is huge (the total of your ram plus however much hard drive space that windows has allocated for virtual memory). you put something on the heap like this:

int *foo = new int;

now foo will point to memory on the heap. in general when you have big arrays you''ll want to put them on the heap or your app will run out of memory. so:

//this is bad
char myArray[10000];

//this is good
char * myArray = new char[10000];

however, when dealing with pointers it is essential to remember that YOU are responsible for freeing the memory that you get. any call to new should have a later call to delete when you are done with the variable:

int * foo = new int;
char * myArray = new char[10000];

//do some stuff with those variable. maybe across multiple
//functions, maybe you keep the memory for a while, maybe for not
//that long

//now release the memory
delete foo;
delete[] myArray;

-me

Share this post


Link to post
Share on other sites
Inmate2993    222
One little note the dude above me forgot to mention.

Pointers and Arrays, in terms of functionality, are identical. Specifically, the name if the array is the pointer, and the pointer points an an array. So, say you declare that block of memory.

j = new int[256];

You can use j like a pointer, and an array.

*(j+128) = 5;
j[128] = 5;

These are the same. Also, when you declare a static block of memory on the stack, as so:

int k[20];

*(k+19)=5;

Thats valid also. The only distinction here is that theres no pointer k, it''s something the compiler keeps track of, so, you can''t use the address operator (&) to get the address of k, since it doesn''t exist during runtime.

Share this post


Link to post
Share on other sites
Agony    3452
Like the two guys above said, but in my own words, pointers have two main purposes:

Dynamic Memory - memory from the heap, that can be allocated and deallocated while the program runs. This allows you to use only as much memory as you need, and lets you determine how much you need while you run the program, and not just when you compile the program. The pointers are needed since the location of the dynamically allocated memory on the heap could change every time you run the program, so in this case, you do need to know where the memory is. That''s why new, malloc, etc. all return pointers.

Referential Data Structures - pointers provide a way for one object to reference another object. For example, let''s say that you want to model the human figure. You start with a struct or class that represents the torso. The torso needs to say that it has a head, two arms, and two legs attached to it. These five things are other objects in memory. By using pointers to these objects, the torso can specify which objects are attached to it. Most non-trivial data structures need pointers. A linked list, mention by Palidine, is one of the more simple ones. Each item in the list contains that item''s data, and a reference (pointer) to the next item in the list. Without the ability to have such a reference, there would be no way to create a linked list.

And there is one other common way to use pointers. They can be used as arguments to functions. Instead of passing a 1024-byte structure as an argument to a function, you can pass a 4-byte pointer instead. It save lots of memory bandwidth, and/or it allows you to modify the variable from within the function, so that the changes will still be visible from outside the function. Otherwise, you simply pass in a copy of the variable, the copy gets changed, but the original never gets touched. In C++, you can use references instead of pointers to accomplish this, but technically, references are just pointers anyway. The language just hides them a little bit.


int Agony() { return *((int*)0); }    Mwahaha... >8)

Share this post


Link to post
Share on other sites
jedis1000    122
Thanks you guys. I think I understand them a bit better now. To finish this all off, do you think you could give me an example of a program where it would be a good idea to use pointers?

Share this post


Link to post
Share on other sites
alnite    3436
quote:
Original post by jedis1000
My definition of a pointer would be a variable that "points" to another variable in the memory. This address is then stored in that pointer''s variable.
No. A pointer is a variable that points to an address in the memory, regardless of whether that address is occupied by a variable or not. It can point to anything, even junks.

int* pint;

pint can point to anything.

int* pint;
int my_var;
pint = &my_var;

now pint points to the address of my_var.


One of the good deals of using pointers are dynamic memory allocation, as already mentioned by Palidine. That''s basically creating variables on demand. Here''s an example:

int* pint;
pint = new int; // creates a new variable of type int.

pint points to the address of an "unnamed" variable of type int. If that variable doesn''t have a name, how are you going to access it without a pointer ?

If you need 20 new int variables, just do:

pint = new int [20];

or even better:

int number_needed = 100;
pint = new int [number_needed];


You can basically create as many variables as you like.

But beware that any new variables that you create, must be freed or destroyed. You can''t just create and forget.

pint = new int;
delete pint; // delete one "unnamed" variable

pint = new int [20];
delete [] pint; // delete 20 "unnamed" variables

If you are wondering why you don''t need to delete the regular variables, for example, like int my_var, the compiler does that for you already. When your program starts, the program creates my_var. When the program ends, it deletes my_var. If you are using pointer, you are the one responsible for this.

Share this post


Link to post
Share on other sites
alnite    3436
quote:
Original post by jedis1000
Thanks you guys. I think I understand them a bit better now. To finish this all off, do you think you could give me an example of a program where it would be a good idea to use pointers?
Windows Explorer. The number of files and folders are determined when the program starts. The programmers of Windows Explorer have no clue how many files folders your computer has. Imagine you are making a Windows Explorer. You need to somehow store the folder''s name. How many folders are you going to have? No clue. You can''t do that with simple array.

Folder all_folders[1000];

What if it''s more than 1000? What if it''s 10000? What if it''s 100000?

Share this post


Link to post
Share on other sites
jedis1000    122
I get it now. Pointers are good for making varaibles on-the-fly, and pointing to addresses in a computer''s memory. Thanks for the help on this one.

Share this post


Link to post
Share on other sites
GroZZleR    820
Static objects are also passed as 'copies' of themselves to functions.

For example:

void ChangeNumber(int iNumber)
{
iNumber = 5; // This is changing the value of the local copy of iNumber, not the variable passed in.
return;
}

int main(void)
{
int iSomeNumber = 50;
ChangeNumber(iSomeNumber);
std::cout << iSomeNumber << std::endl; // This prints 50, not 5 as you might expect.

return;
}


But if you alter ChangeNumber to take pointers, it can change the value of the number (which in some situations is handy).


void ChangeNumber(int *piNumber)
{
*piNumber = 5;
return;
}

int main(void)
{
int *piSomeNumber = new int;
*piSomeNumber = 50;
ChangeNumber(piSomeNumber);
std::cout << piSomeNumber << std::endl; // This prints 5
delete piSomeNumber;
return;
}


Might not seem relevant now, but it will be soon enough as you get into bigger projects. (Also, Structure->Value is way cooler than Structure.Value ^_^)

[edited by - GroZZleR on March 23, 2004 1:13:37 AM]

[edited by - GroZZleR on March 23, 2004 1:14:56 AM]

Share this post


Link to post
Share on other sites
Oluseyi    2103
quote:
Original post by GroZZleR
<Poor use of pointers>
Use a reference, unless you''re programming in C.

quote:
(Also, Structure->Value is way cooler than Structure.Value
No, it''s two characters instead of one, redundant and ugly.

Share this post


Link to post
Share on other sites
Oluseyi    2103
quote:
Original post by RuneLancer
That''s fully subjective.
Then how about "it''s confusing; having a single member access operator regardless of reference type creates no ambiguity"?

Share this post


Link to post
Share on other sites
Oluseyi    2103
quote:
Original post by RuneLancer
You know, as a moderator, one would expect a little more maturity.
What does that even mean? You made a subjective, inaccurate comment and I refuted it, then you accuse me of "immaturity"? Is it suddenly cool to bash moderators or what?

There is no valid reason to have two member reference operators. The D programming language has shown that implementing a single operator is possible (and trivial). Indeed, the ambiguity created by the presence of two different means of getting at the same thing has spawned entire threads on the topic. Granted, it''s a feature of the language, but it''s not a good one - nor is it "cooler", as you allude: it''s twice as many characters, inconsistent with any other programming language and has no redeeming features.

Since I''m a nice guy, let me say this clearly: I''m getting tired of taking flak from ignorant posters. Don''t make me vindictive; it''s never pretty.

Share this post


Link to post
Share on other sites
RuneLancer    253
I suggest you drop the matter. You really ARE making yourself look immature by trying to drive in a point that not only has little to no relevance to the OP''s question, but is also truly a matter of personal preference that has very little impact on a program''s final performance. Moderator or not. Furthermore, I fail to see where this is going. Peace.

To return to the OP''s question, no-one has brought up function pointers. That''s an other application pointers get, though it''s less frequent than using them to manage dynamic variables. You can create a reference to a function and call that function, then change the pointer on the fly to call an other function. They can be used to replace switch/if statements (not sure you''d want to do that though; you''d probably take performance hits and your could would most likely lose clarity anyways), realize late-binding, or implement callbacks.

Although you can find much better ways to replace function pointers and probably won''t need them, there are still a number of uses for them in C.

Share this post


Link to post
Share on other sites
Zahlman    1682
quote:
Original post by Oluseyi
There is no valid reason to have two member reference operators. The D programming language has shown that implementing a single operator is possible (and trivial).


As has Java, yes?

Share this post


Link to post
Share on other sites
markr    1692
The reason we use pointers is so that we can keep anonymous things around in arbritary quantity.

These are normally used (in the context of games) for anything which there is likely to be >1 of at once, for example, the bad guys, or items on a level.

We don''t want to have a fixed maximum number of them (like if we used a normal array) - so we''d normally use a linked list (or indirectly, through STL).

Additionally, we can use them as references, when we have one item of some kind which needs to remember some relationship to some other item - like a guided missile remembering what its target is. That way, it doesn''t need to try and find a new target each time around the main loop, it can just keep aiming at the same one.

In practice this is very common in games, we have RPGs where everyone belongs to a party, and monsters are chasing a target, items belong to people, NPCs have things too, so in practice we tend to use pointers a lot.

Mark

Share this post


Link to post
Share on other sites