• Advertisement
Sign in to follow this  

Pointers? What's the point?

This topic is 4794 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

Back when I took my C Programming class a couple years ago, I breezed by without any trouble what-so-ever. That is, except for pointers and addresses. As I took the class, I honestly didn't see any use for these in the near future (espescially not for game development) so I basically dismissed them after the semester ended. Well now that I'm reading over this C++ book that I got, they happen to stress heavily on the importance of the pointer. Not only that, while I was browsing the book "Role Playing Game Programming with Direct X", they specifically mentioned pointers as something you need to have a solid grasp on. Am I missing something? Why would you ever need to know the memory address of a variable? If you're going to substitute a variable, why not just replace the entire variable altogether instead of replacing the contents of where it's located in memory? I honestly don't understand the benefits of using pointers and addresses, and I still find it to be the hardest code to understand. Does anyone have any insight as to why they're so crucial or maybe can possibly offer a very easy to learn article about them? Thanks. -Kronikle

Share this post


Link to post
Share on other sites
Advertisement
Pointers give you full control of memory. Without that you can't utilize the use of memory to its full power.

Its analogus to saying: why would a car engine engineer need to know anything about the chemical and physical reactions that take place in an engine cycle.

Pointers do make code more complicated but good use of them gives u more functionality , speed and better memory use.

Try programming any project over 10 000 lines of code and you'll see.

Share this post


Link to post
Share on other sites
Quote:
Original post by Kronikle66
I honestly didn't see any use for these in the near future (espescially not for game development) so I basically dismissed them after the semester ended.

I'm not sure how you could conclude that games in particular wouldn't need pointers. Is there a solid reason why you assumed that?

If you had a situation where you knew exactly how much memory you needed for your entire game then you could probably just about get away without using pointers but it would be messy and would be far more trouble than it's worth.

Usually in a game you will be varying things at runtime. The amount of polgygons loaded from a map, the amount of enemies in a level, the amount of players in a network game, the amount of live bullets in the world, etc.

These things will have memory associated with them. The way of refering to all the bullets isn't to have a load of different variables called bullet1, bullet2, bullet3, etc, but to have some container of bullets which you can loop through. You refer to an individual by pointer (or reference, which is similar but different too).

This makes it possible to add and remove things as and when you need to. And it means you don't have to make a copy either. Assigning a memory address to a pointer is quick as it's (likely to be) only 4 bytes, whereas an Enemy or a Bullet may have a lot of memory associated with it, position, direction, strength, badness, etc. Copying that will take longer. So there are reasons of efficiency too. However the main thing, in my book is simplicity.

Having said all that though, as you use the more advanced and useful features of c++ you may come to use pointers less. The standard library has containers which will look after all memory allocation/deallocation for you. As long as you've correctly constructed your classes you can do this kind of thing, dynamically:


#include <list>
#include <string>

class MyClass {
std::string m_name;
public:
MyClass(const std::string& name)
: m_name(name) {
}
};

int main() {
std::list<MyClass> container;
container.push_back(MyClass("petewood"));
container.push_back(MyClass("Kronikle66"));
return 0;
}


Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Pointers are necessary for dynamic memory allocation. If you know your program is going to need a block of memory, but you don't know how much you'll need until run-time, you have no choice but to dynamically allocate it:

some_type * mem = new some_type[size];

Pointers are also necessary for writing interfaces. If you're writing the renderer for your game and want to be able to pass it different objects to render, you would not want to be stuck writing a different render_object() function for each object type:

render_object(const Bullet & b);
render_object(const PlayerCharacter & pc);
...

Rather, you would want to write a single render function that accepts a pointer to and object, and then pass each object's memory address as the parameter:

render_object(Object * obj);

Object * o = new Bullet;
render_object(o);
Object * pc = new PlayerCharacter;
render_object(pc);

Share this post


Link to post
Share on other sites
Say you have a rather large structure, and you need to pass that structure to a function. What do you think is better? To create another copy of that structure on the stack, or to pass a pointer to the structure (pointers are always the same size, and rather small).

As far as understanding them, most books I've read give piss poor examples of how, why, and when to use them. For example, doing something like:



int x = 5; // initialize x to store 5
int* y = &x; // initialize a int pointer (int *) to store the address of x (&x)

*y = 4; // set the value pointed to by y (*y) to 4, making x = 4



is just about pointless. Unfortunately, this is how most books/tutorials teach it. I guess the reasoning is to make pointers a bit easier to grasp. A better example, imo, is showing how passing the address of a variable to a function allows the function to manipulate the actual variable and not just a local copy.

You probably already understand how this works, however.

Another example:

Arrays in c/c++ are great, but they're static. A static array is only useful if you know _exactly_ how much data you need to store. To create a dynamic array, however, requires the use of pointers.

Here's an example of a dynamic 2-dimensional array wrapped in a templated class:


template <class Datatype>
class Array2D
{
public:
Array2D(int p_width, int p_height)
{
m_array = new Datatype[p_width * p_height];
m_width = p_width;
m_height = p_height;
}

~Array2D()
{
if(m_array != 0)
delete[] m_array;
m_array = 0;
}

Datatype& Get(int p_x, int p_y)
{
return m_array[p_y * m_width + p_x];
}

bool Resize(int p_width, int p_height)
{
Datatype* newarray = new Datatype[p_width * p_height];
if(newarray == 0)
return false;

int x, y, t1,t2;
int minx = (p_width < m_width) ? p_width : m_width;
int miny = (p_height < m_height) ? p_height : m_height;

for(y = 0; y < miny; y++){
t1 = y*p_width;
t2 = y*m_width;
for(x = 0; x < minx; x++){
newarray[t1+x] = m_array[t2 + x];
}
}

if(m_array != 0)
delete m_array;

m_array = newarray;
m_width = p_width;
m_height = p_height;

return true;
}

int Width() { return m_width; }
int Height(){ return m_height;}

int Size() { return m_width * m_height; }




private:
Datatype* m_array;
int m_width;
int m_height;
};



You see how I'm using pointers to store the beginning address of the memory allocated by new? Also, notice the Get method. It returns the "address of", which means you can do something like:

Array2D<int> test_array(10,10);
test_array.Get(5,5) = 10;
cout << test_array.Get(5,5) << endl; // prints out 10


There are many uses for pointers. If you're going to be using c or c++, understanding pointers is an absolute must.



Share this post


Link to post
Share on other sites
Try creating 32mb of usable memory without using pointers. Better still, trying returning this block of memory from a function.

Other languages have other methods of dealing with these things. Garbage collection. Implicit deterministic sorts of things (I count c++'s stl as an incomplete attempt at this). C is too simple for these. It leaves it up to the programmer.

Share this post


Link to post
Share on other sites
Pointers are almost not necessary in C++. They may be useful in some cases, but I'm still wondering if iterators, auto_ptrs or shared_ptrs and references could not be used to almost entirely replace pointers in a game. The only places where pointers would need to be used is when interfacing with pointer-using APIs, or when allocating memory, but this is in my opinion marginal.

Still, they are a necessary and very important part of C, and they are not dead yet in C++, so if you plan to actually use these languages seriously, I suggest you learn these basic parts of the language in order to have more options.

Share this post


Link to post
Share on other sites
Quote:
Original post by C-Junkie
Try creating 32mb of usable memory without using pointers. Better still, trying returning this block of memory from a function.
Real World example: image editing program. Should the [usually very large (8MB+)] pixel buffer be on the stack or on the heap? Hint: heap.

Share this post


Link to post
Share on other sites
/overwhelmed

I have to thank you guys for the incredibly replies. But, as usual, leave it to this board to make me look like a complete newbie lol. I understood about 60% of what you guys said.

I guess I better learn more about them before I try to find a use for them. ontheheap's example of how the tutorials teach them is basically how I learned. Well, time to learn a little more about them. Then I'll come back and review what you guys said.

-Kronikle

Share this post


Link to post
Share on other sites
Quote:
Original post by ToohrVyk
Pointers are almost not necessary in C++. They may be useful in some cases, but I'm still wondering if iterators, auto_ptrs or shared_ptrs and references could not be used to almost entirely replace pointers in a game. The only places where pointers would need to be used is when interfacing with pointer-using APIs, or when allocating memory, but this is in my opinion marginal.


Even if you are using iterators and smart pointers you'll still have to access the data using pointer syntax:

SmartPtr ptr(new Thing);
ptr->DoSomething();

I do prefer using references wherever possible and only pointers when necessary, which is usually as you say, with legacy APIs.

Using references means you put the onus for checking the validity of the data on the person giving it to you.

Share this post


Link to post
Share on other sites
Quote:
Original post by Kronikle66
Am I missing something? Why would you ever need to know the memory address of a variable? If you're going to substitute a variable, why not just replace the entire variable altogether instead of replacing the contents of where it's located in memory? I honestly don't understand the benefits of using pointers and addresses, and I still find it to be the hardest code to understand.

Does anyone have any insight as to why they're so crucial or maybe can possibly offer a very easy to learn article about them?

Thanks.

-Kronikle
Try looking up previous posts e.g. http://www.gamedev.net/community/forums/topic.asp?topic_id=178153

Basically, you can't do Jack without them in C++! It would be like not travelling by any other means other than on foot. You aren't going to get very far, and there are a lot of places you can't get to at all.

Share this post


Link to post
Share on other sites
Three words: Recursive Data Structures.

Recursive data structures include lists, trees, and graphs.

(using Haskell syntax, which is pretty clear if you're familiar with math)

data List a = Nil | Cons a (List a)
data Tree a = Leaf a | Branch a (Tree a) (Tree a)
data GraphNode a = Node a [Node a]


In C++ terms, these things would need to be implemented in terms of pointers.

struct ListNode {
DataType nodecontents;
listNode* next;
}

struct TreeNode {
DataType nodecontents;
TreeNode* left;
TreeNode* right;
}

struct GraphNode {
DataType nodecontents;
std::vector<GraphNode> edges;
}


I know there is stuff in the standard libraries for some of this, but these are trivial examples. Without pointers, your data would need to have a structure that is strictly hierarchical (classes within classes with vectors, etc.), and that could be purely determined at compile time.

Share this post


Link to post
Share on other sites
References in C++ and Java are 'pointers' too...altough Java uses a sort of C++ 'smart pointers'!
If you write a program you must use data and the only way to access data is use their memory address!
And without pointers some problems are impossible to resolve (as Flarelocke wrote).

Share this post


Link to post
Share on other sites
Even if you don't have a great grasp on pointers, you need to know what they are. Most APIs use pointers often to access the computer's resources. For instance, Win32 has handles which are the same as pointers and are used to access the screen and bitmaps, and just about everything else.

Share this post


Link to post
Share on other sites
The problem with a lot of pointer tutorials or cs classes, is they don't really make a good case for what you actually use pointers for, and how much you will use them. Once you become familiar with pointers, and continue programming more, you will realize you could not live without them.

Share this post


Link to post
Share on other sites
Quote:
Original post by Kylotan
"Pointers - because it's easier to give 2 people your address than to duplicate your house."


This is the greatest quote ever! (btw, is this an original quote? or else where did you hear it?)

Generally, the higher level the language, the less you need to understand pointers. In modern object oriented languages like C++ or Java, it is possible to create programs without ever being aware of them. However, at lower level, the computer makes EXTENSIVE use of pointers.

If you want to understand why pointers are essential to computing, try learning about an assembly language.

If you look around, you'll find that most computer architectures can only move 4 or 8 bytes at a time (DMA and STRING commands aside). For example, a CPerson class that may take 24 bytes for a name, 4 bytes for an age, 4 bytes for a gender. Such a trivial-seeming class takes up 32 bytes which would require 8 MOV commands on a 32-bit Intel processor. If you are constantly passing CPerson objects to a function, that can take a lot of time for such a small class!

Instead, what a smart programmer would do would be to pass a pointer instead of copying the object. "To pass a pointer" means to take the address of the object (actually the address of the first byte of the object) and pass THAT instead. That takes only one MOV command for the processor. In addition to this, the function can use the pointer to change data in the original object (where if you copied the object, you would have to copy it back to save changes).

In low level languages like C and C++, pointers are probably the most common cause of Runtime errors and are someone difficult to trackdown. Therefore in more modern laguages, pointer usage is often carefully restricted.

In modern OOP languages, pointes still exist, but they aren't called pointers. Whenever you pass by reference, you are actually passing by a pointer. Whenever you instanciate an object in Java or C#, you are creating an object on the heap and receiving a Pointer to that object.

Hope that helped ^^;

Share this post


Link to post
Share on other sites
Quote:
Original post by Tac-Tics
Quote:
Original post by Kylotan
"Pointers - because it's easier to give 2 people your address than to duplicate your house."


This is the greatest quote ever! (btw, is this an original quote? or else where did you hear it?)
LOL![lol]
I agree. Brilliant!

Share this post


Link to post
Share on other sites
I made the quote up last night, but I think it paraphrases a much longer and less amusing example I read somewhere in a tutorial which was trying to explain the benefits of references in programming languages.

Share this post


Link to post
Share on other sites
Quote:
Original post by Kronikle66
/overwhelmed

I have to thank you guys for the incredibly replies. But, as usual, leave it to this board to make me look like a complete newbie lol. I understood about 60% of what you guys said.


Okay, not to be rude here, but if you don't understand pointers in C++ you are a newbie.

To be really, brutally honest it sounds like you have an ego problem: you completely dismissed pointers without understanding them? you feel you have an elevated level of competency in C++ despite not understanding pointers?

If there's one thing I've learned in the last five years or so, it's that no matter how much you think you know you've always, ALWAYS got more to learn. Sometimes you surpass your peers, sometimes you look on in awe at others doing the most amazing things with their code.

Quote:
Original post by Kronikle66
Am I missing something? Why would you ever need to know the memory address of a variable?


Actually knowing the memory address of a variable is generally unimportant to you as a programmer (though it may come in useful in the debugging side of things).

Quote:
Original post by Kronikle66
If you're going to substitute a variable, why not just replace the entire variable altogether instead of replacing the contents of where it's located in memory?


You've got to walk before you can run. You've got to know C++ fundamentals before you write games in C++.

Stop reading the book you're reading and go learn C++ properly, before declaring yourself all clued up.

You might be surprised at just how much else you missed.

Share this post


Link to post
Share on other sites
Quote:
Original post by krumms
To be really, brutally honest it sounds like you have an ego problem: you completely dismissed pointers without understanding them? you feel you have an elevated level of competency in C++ despite not understanding pointers?

That was more brutal than anything else. An ego problem? That's completely out of left field. The guy never mentioned he thought he had an elevated competency in C++. In fact the exact opposite was implied when he said he was reading through a C++ book he got. Second, if you happen to take a C programming class with a poor instructor who doesn't teach pointers well enough or undervalues their importance, than what's to keep someone from dismissing them? It would only make sense for a student to assume that something's importance is relative to how much analysis it's given. From reading his first post it sounds as though the instructor didn't spend much time expounding their usage or importance, otherwise he wouldn't have initially shrugged them off. Which is unfortunate, however I wouldn't fault him for it. This brings me to my last point: if you took a semester of C and felt competent in generally every area except for one which wasn't explored in depth, then you wouldn't feel as though you were a newbie either. Maybe you wouldn't feel like a complete expert either, but it's not the same feeling as being totally lost.

As far as I'm concerned this is a classic "Why use pointers?" thread with the usual inquiries. However it's humility has been shattered by accusations of ego problems! [crying]

Share this post


Link to post
Share on other sites
Perhaps I was a bit harsh. Sorry OP, I'm tired :-P

Never the less, the main focus of my cranky little rant stands:

Don't dismiss or disregard potentially valuable information before you truly understand it.

That goes for programming, maths, life, etc.

I shall say no more before I offend anyone else :-)

Share this post


Link to post
Share on other sites
So true. However with some fields, especially those are large as math and computer science you need someone to tell you what's important to know and what isn't that important to know. Otherwise there isn't enough time to learn everything! [smile]

Share this post


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

  • Advertisement