Skip to main content
GameDev.net gamedev.net
🔒 Locked

Pointers? What's the point?

Started by Kronikle66 Jan 7, 2005 at 2:15 PM 24 replies 7.3k views
Original Post
Kronikle66
Kronikle66
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
-Kronikle
Radan
Radan
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.
-----------------Always look on the bright side of Life!
Qw3r7yU10p!
Qw3r7yU10p!
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;}
ontheheap
ontheheap
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 5int* 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 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.



C-Junkie
C-Junkie
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.
ToohrVyk
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.

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.
flangazor
flangazor
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.
Kronikle66
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.

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
-Kronikle
Alpha_ProgDes
Alpha_ProgDes
we've had a rash of "why use pointers?" posts lately.
i hope the search function works soon.
Beginner in Game Development?  Read here. And read here.  
Qw3r7yU10p!
Qw3r7yU10p!
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.
iMalc
iMalc
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.
Flarelocke
Flarelocke
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.
---New infokeeps brain running;must gas up!
blizzard999
blizzard999
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).
Kylotan
Kylotan
"Pointers - because it's easier to give 2 people your address than to duplicate your house."
Stompy9999
Stompy9999
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.
corrington_j
corrington_j
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.
Tac-Tics
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?)

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 ^^;
iMalc
iMalc
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!
Kylotan
Kylotan
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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.