Archived

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

kaiel090x

Why the hell does anyone need to know pointers?

Recommended Posts

What the hell is a pointer for. Finding the address of a variable, I know, but for what damn reason. Can someon: Give me acouple answers as to how a pointer can help my programming. And if I will ever need them for games. ~ from the depths of the ocean

Share this post


Link to post
Share on other sites
You can allocate memory at run time:

int* p = new int[50];

Commonly, you don''t know how much memory you will need in an application, therefore you will need to be able to allocate more memory if needed.

Another use:

struct hog{
double[5000];
};

void f(hog h);
void f(hog* h);

...
hog aHog;

f(aHog); /* slow, must copy 5000 doubles */

f(&aHog); /* fast, only must copy a 32-bit int */



ECKILLER

Share this post


Link to post
Share on other sites
Pointers also allow you to perform arithmetic on the actual variable's address to a much greater extent than available to automatic and static variables. Also, one pointer variable could be used as an array if enough memory has been allocated.

Math.

Edited by - Mathematix on August 11, 2001 6:44:38 PM

Share this post


Link to post
Share on other sites
Hmmm... Pointers, eh? The word "Virus" comes to mind immediatly... But seriously, Pointers are one of the things that make C such a powerful language. Besides, even if all your doing is a bunch of printf()/scanf() statements, you still ned a basic knowledge of poiter usage. (thats what the & symbol is there for!)

-----------------------------

Vash the Stampede

"Love & Peace!"

Share this post


Link to post
Share on other sites
Guest Anonymous Poster

Pointers are also great to pass to a function that requires a lot of parameters. Er, I mean, you pass pointer to your params, instead of the params themselves.

Here is some code to ''splain:

  

// here is my parameter structure:


struct ParamStruct
{
int x;
int x2;
int y;
int y2;
char stuff;
char other;
};

// now here is a function that uses the above params


int NeatFunction(ParamStruct* ps)
{
// code that uses params

}

// to call my function, I''d do this:


ParamStruct ps;

ps.x = 10;
ps.x2 = 20;
ps.y = 30;
ps.y2 = 40;
ps.stuff = 50;
ps.other = 60;

int result = NeatFunction(&ps);



Now instead of passing six params, I just pass one. I use this specifically in a multi-purpose blitter function I wrote, where the majority of the blitter params stay the same from call to call, and only one or two params change at a time. Seems more efficient.




Share this post


Link to post
Share on other sites
Hi,
Here are some things pointers are good for:

Dynamic memory allocation
int *p = new int[256];

Linked lists ( basically dynamic memory allocation ^-^ )
Binary trees
Changing values in a function ( C++ uses reference parameters for this ).

...But mostly, dynamic memory allocation :-D It''s fun. You''ll love it.

--Nairb

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
people always forget to list the most important reason: pointers create relationships.

Let''s say you have a Monster class/struct. It has an x and y coordinate, hit points, and a current target. For x,y and hp we use ints. What do we use for current target? We use a pointer to whatever it can target. We can''t use a variable and set it equal to whatever we want to target. That would make a copy. By using a pointer our monster "knows about" a target, he doesn''t "have" a target. There are lots of different kinds of relationships and pointers are used for many of them. Some other relationships:

"has": this means that the data is part of a greater whole, the x variable in a point struct is part of the point. We use normal instance variables for the has relationship

"knows about" here we usually use pointers, though I think references would work for static relationships

"owns" this one is also done with pointers, but here there is a responsibilty for creation and destruction

"is a" where one type is a subtype of another, use inheritance

those are the basic ones, when deciding how model something think about what kind of relationship you are making.

Share this post


Link to post
Share on other sites
I''ll try to sum it up as best as I can...

1. Pointers can hold the address of a named variable, like in the following example:

int integer;
int* pInteger;
pInteger = &integer;

In this example, modifying *pInteger would be the same as changing integer.
However, pointers can also be used when you don''t know how many of something you need. For example, say you had a class that stored pictures along with associated data (size, bit depth, etc). One way to store these in a program would be to arbitrarily size an array of them. Since arrays are created the second you define them, this immediately uses a lot of space. If you used pointers, however, you could allocate space as you need it, wasting nothing. This is precisely what linked lists are for, by the way; want another photo? Just tack it on to the end of the list. I''ll leave making a linked list to another thread, though.

2. Poiners can be passed through functions instead of their variables. Instead of passing, say, a 100MB structure into a function (which means making a copy of the data for the function to work with), you can pass a 4 byte pointer to the original data. Much faster in the end, guaranteed.

3. If you plan on programming games, I suspect you''ll use an API such as OpenGL or DirectX (if you don''t use any APIs...well, God help you ). I don''t know about OpenGL, but DirectX uses pointers like crazy, so you''ll probably have to learn their syntax, if not their use, anyway.

If you still don''t get their overall use, letme put it this way...
Have you ever had one of those moments, where you''ve been sitting and staring at a problem for hours, and you''re about to nod off into Never-Never Land, when all of a sudden, something happens, a light goes on overhead, some angels start singing "Hallelujah!", and you smile a smile reserved for the greatest moments of your life, and everything suddenly came together in your mind? (Woah, my English teacher would have me dragged into the street and shot for that sentence ) Figuring out the use of pointers was my first programming-related moment. (Classes, OOP, and its use was my second.) Trust me, it''ll all come to you eventually. And you will smile. And all will be good.

-Normie

PS. Those "moments" I went on about...what''s the word for those? Euphony?


I am a devout follower of the
"Lazy Programmer''s Doctrime"(tm)...
and I''m damned proud of it, too!
-----
"I came, I saw, I started making
games." ... If you''ll excuse
me, I must resume my search
for my long lost lobotomy stitches.

Share this post


Link to post
Share on other sites
Ahhh yes.... I remember that moment. My suggestion is not to try to understand how pointers work at a physical and intermediate level, but just in a more generalized, abstract way. And the moment will come, and you''ll slap your head and start laughing. Maybe that angel will be singing, too

The difference between pointers and the data they point to is just that...the pointer holds where something is, and the data itself is what something is. Try to understand this different between "what" and "where", and you will figure it out in no time.

Share this post


Link to post
Share on other sites
<controversial>Pointers are also the cause of 90% of the crashes in software today So many crashes are due to bad pointer dereferencing. Of course, this isn''t a problem with pointers, it''s a problem with the people that use them.</controversial>

Share this post


Link to post
Share on other sites
In regard to Kylotan''s post, one thing that I have trouble understanding when it comes to pointers is when to dereference or not. I can never remember when to put the little asterik thingy or to leave it off.

But then again, if you''ve read some of the other posts I''ve made or threads I''ve started, that should come as no surprise

Share this post


Link to post
Share on other sites
The primary use of the pointer that made me wake up to why they are useful is this: If you do not use pointers or references as parameters of your functions, it has to make a copy of each.

This really sucks, as above somewhere, if you are passing a large structure. Pointers negate that disadvantage by giving the function the address where the structure is located, so it can just read or change it at its convenience, without having to copy the whole structure itself.

For similar reasons, you can use pointers to functions. In game programming this applies generally to situations where you have hardware-specific code. If there is a function called throughout the game, especially if called often, and that function varies depending on the hardware on the user''s system, you don''t want to have to check which function to call every time you need it - ie -
if (somehardware) function1();
else function2();

Instead, when your program is initialized, you set a pointer to the function that will be used each time, so that you have to use only one function name in your program. If you''re having trouble thinking of what kind of hardware specific code you might need, chew on this: You want to optimize the code to run great on a Pentium processor, specifically (say you''re writing for the P4 or something.) To take advantage of some of the features of the P4 processor for a particular function, you would potentially create problems for those not utilizing a P4. As such, you would want to ensure that your code worked well on other chipsets.

While this is not the only application, or necessarily even the best one, I just wanted to give another use for pointers.

Share this post


Link to post
Share on other sites
quote:
Original post by Anonymous Poster

Pointers are also great to pass to a function that requires a lot of parameters. Er, I mean, you pass pointer to your params, instead of the params themselves.

Here is some code to ''splain:


    

// here is my parameter structure:


struct ParamStruct
{
int x;
int x2;
int y;
int y2;
char stuff;
char other;
};

// now here is a function that uses the above params


int NeatFunction(ParamStruct* ps)
{
// code that uses params

}

// to call my function, I''d do this:


ParamStruct ps;

ps.x = 10;
ps.x2 = 20;
ps.y = 30;
ps.y2 = 40;
ps.stuff = 50;
ps.other = 60;

int result = NeatFunction(&ps);



Now instead of passing six params, I just pass one. I use this specifically in a multi-purpose blitter function I wrote, where the majority of the blitter params stay the same from call to call, and only one or two params change at a time. Seems more efficient.




passing a Reference would actually be faster then that ie

    

// here is my parameter structure:


struct ParamStruct
{
int x;
int x2;
int y;
int y2;
char stuff;
char other;
};

// now here is a function that uses the above params


int NeatFunction(ParamStruct & ps)
{
// code that uses params

}

// to call my function, I''d do this:


ParamStruct ps;

ps.x = 10;
ps.x2 = 20;
ps.y = 30;
ps.y2 = 40;
ps.stuff = 50;
ps.other = 60;

int result = NeatFunction(ps);




as no doubt been described i this post that there are 2 ways of giving data to a function pple dont usually remeber there are 3 and or use them!
using refrences are FASTER than pointers as u have impliced (direct) acces to ''ps'' as with a pointer u get explicit acces to object ''ps''. so what this meens is that when iu accesthe data from withinps u use the ''.'' instead of ''->''


~prevail by daring to fail~

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
quote:
Original post by Zerosignull
[quote]Original post by Anonymous Poster

Pointers are also great to pass to a function that requires a lot of parameters. Er, I mean, you pass pointer to your params, instead of the params themselves.

Here is some code to ''splain:


      

// here is my parameter structure:


struct ParamStruct
{
int x;
int x2;
int y;
int y2;
char stuff;
char other;
};

// now here is a function that uses the above params


int NeatFunction(ParamStruct* ps)
{
// code that uses params

}

// to call my function, I''d do this:


ParamStruct ps;

ps.x = 10;
ps.x2 = 20;
ps.y = 30;
ps.y2 = 40;
ps.stuff = 50;
ps.other = 60;

int result = NeatFunction(&ps);



Now instead of passing six params, I just pass one. I use this specifically in a multi-purpose blitter function I wrote, where the majority of the blitter params stay the same from call to call, and only one or two params change at a time. Seems more efficient.




passing a Reference would actually be faster then that ie



// here is my parameter structure:


struct ParamStruct
{
int x;
int x2;
int y;
int y2;
char stuff;
char other;
};

// now here is a function that uses the above params


int NeatFunction(ParamStruct & ps)
{
// code that uses params

}

// to call my function, I''d do this:


ParamStruct ps;

ps.x = 10;
ps.x2 = 20;
ps.y = 30;
ps.y2 = 40;
ps.stuff = 50;
ps.other = 60;

int result = NeatFunction(ps);




as no doubt been described i this post that there are 2 ways of giving data to a function pple dont usually remeber there are 3 and or use them!
using refrences are FASTER than pointers as u have impliced (direct) acces to ''ps'' as with a pointer u get explicit acces to object ''ps''. so what this meens is that when iu accesthe data from withinps u use the ''.'' instead of ''->''


~prevail by daring to fail~

Share this post


Link to post
Share on other sites
Pointers are wonderful. I don't understand how you can NOT understand them! But don't feel insulted, because very few peope DO understand them when they first hear about them. And that, like I said, mystifies me. It's not even as though I am a veteran programmer who has grown used to pointers; I'm rather new to this stuff, but I understood pointers and their real uses very quickly! Don't get me wrong; I'm not a great programmer (far from it) and I have a LOT left to learn (I don't appreciate classes enough, for one thing); I just like pointers. They're fun. (Hell, I'm not doing this for a living, it has to be fun or I wouldn't do it! I just hope it doesn't change when [or if] I get a job doing it.) But anyway, enough of that. Here are some uses for pointers.

      

//Arbitrary, un-balanced tree structures (Well, that's generally

//a bad thing, but sometimes you might need something like this):



struct node
{
int value;
node ** children; //Pointer to a pointer to a node, which will be an array of pointers to nodes.

};


//Why have a pointer to a pointer? So you can have an array of

//pointers. And what's a multimensional array but an array of

//pointers to pointers? And what's an array, period, but a

//pointer with fancy syntax? All array[30] is is a pretty

//version of *(array + 30).


//Or let's say you want to pass a single row of a matrix to a

//function. How do you do it?



float ** matrix = new float[10] //Dynamically allocates a 10x20 array.

for(int i = 0; i < 10; i++){matrix[i] = new float[20];}


//Now, you want to pass just a row to SomeFunction. That's as

//simple as this:



SomeFunction(matrix[rownumber]);
//OR

SomeFunction(*(matrix + rownumber));


//And, best of all, you're not sending 20 floats to

//SomeFunction, but only a pointer!


//And if you want to access a single element of the matrix, you

//could either do the following:



n = matrix[y][x];

//OR


n = *(*(matrix + y) + x);



I hope someone benefited from that little demonstration...

Edited by - TerranFury on August 12, 2001 5:17:06 PM

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
thankyou thankyou thankyou thankyouthankyouthankyou thankyou thankyou thankyou thankyou thankyou thankyouthankyouthankyou!!!!!!!!!!!! found this forum searching in google for explanations on pointers and at last i understand, i come from a Fortran background so only having just grasped the concept of classes was struggling with pointers.. but i have it now, lightbulb moment!!
thanks

Share this post


Link to post
Share on other sites
quote:
Original post by petewood
this is 2 1/2 years old


maybe but it doesn''t make it any less useful does it? I mean they did decide to achieve all of these so I''m glad that someone found it useful; I was afraid they did it just to slow down the forum search





--{You fight like a dairy farmer!}

Share this post


Link to post
Share on other sites
If you''re making games, pointers will save your life. Here is a quick example. We have player objects, and we have vehicle objects. A player has a pointer to a vehicle. When he issues commands (forward, reverse, headlights on) those commands are just forwarded to whatever vehicle his pointer points to.


class vehicle
{
public:
void DoCommands(somestruct);
}

class player
{
public:
player() : m_pMyVehicle(0) {}
void SetVehicle(vehicle* veh) { m_pMyVehicle = veh; }

void DoCommands()
{
if(m_pMyVehicle)
{
m_pMyVehicle->DoCommands(somestruct);
}
}
private:
vehicle* m_pMyVehicle;
}


Now, we can make a player* called ''myplayer'' to represent us... and 2 vehicle* , we call them ''helicopter'' and ''motorcycle''.

Now, we just call myplayer->SetVehicle(motorcycle) and we are driving the motorcycle... vroom vroom, screeeeech... fun right? Now just call myplayer->SetVehicle(heliocpter) and you are in control of the helicopter... Super Simple, very fast, no excess unneeded copying of structs and shifting of data... just change one little number and you are now flying...





Share this post


Link to post
Share on other sites