Whats the deal with pointers eh?

This is a discussion on Whats the deal with pointers eh? within the C++ Programming forums, part of the General Programming Boards category; Hello, I am a learning programmer...I have been practicing on and off for months in java. I understand what a ...

  1. #1
    Registered User
    Join Date
    Aug 2005
    Posts
    266

    Whats the deal with pointers eh?

    Hello, I am a learning programmer...I have been practicing on and off for months in java.

    I understand what a pointer 'does' and the basic mechanics on how to use them.

    But what are their practical uses for a learning programmer like myself?

    The only uses I have seen myself are examples of passing pointers through methods instead of the data itself so that you can run your program faster.
    I also have seen the example of using pointers to complete a linked list.

    Can anyone give me a VERY simple application where pointers are necessary?

    Thanks

  2. #2
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,406

    .

    if you pass an object to a function only a copy will be passed and the object in the calling function remains unchanged,copies are created from the call stack which consumes memory with repeated calls.
    if you instead pass a reference to an object then changes are reflected in the calling function >

    Code:
    #include <stdlib.h>
    #include<stdio.h>
    
    class TestClass
    {
        public:
    
        int testvar_A;
        int testvar_B;
    
    };
    
    void AnyFunction1(TestClass myobject)
    {
        myobject.testvar_A = 25;
        myobject.testvar_B = 50;
    
        printf("Now we are in AnyFunction, testvar_A = %d testvar_B = %d\n\n",myobject.testvar_A, myobject.testvar_B);
    }
    
    void AnyFunction2(TestClass* pMyobject)
    {
        pMyobject->testvar_A = 25;
        pMyobject->testvar_B = 50;
    
        printf("Now we are in AnyFunction, testvar_A = %d testvar_B = %d\n\n",pMyobject->testvar_A, pMyobject->testvar_B);
    }
    
    int main(int argc, char *argv[])
    {
    
        TestClass myobject;
        myobject.testvar_A = 0;
        myobject.testvar_B = 0;
    
        printf("Now we are in main(), testvar_A = %d testvar_B = %d\n\n",myobject.testvar_A, myobject.testvar_B);
    
        printf("Calling AnyFunction1.......\n");
        AnyFunction1(myobject);
    
        printf("Now we are back in main(), testvar_A = %d testvar_B = %d\n\n\",myobject.testvar_A, myobject.testvar_B);
        printf("\n");
    
        printf("** Show the same using pass by reference **\n\n");
        printf("Now we are in main(), testvar_A = %d testvar_B = %d\n\n",myobject.testvar_A, myobject.testvar_B);
    
        printf("Calling AnyFunction2.......\n");
        AnyFunction2(&myobject);
    
        printf("Now we are back in main(), testvar_A = %d testvar_B = %d\n\n",myobject.testvar_A, myobject.testvar_B);
    
        system("PAUSE");
    }
    Last edited by rogster001; 11-13-2009 at 08:03 AM. Reason: add example

  3. #3
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Another place where you'd need to use pointers is if you need an array of elements, but you don't know exactly how many elements you need until runtime (well, technically with C++ you can use vectors to accomplish this, but in C you have no choice)
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
       cout << "How many numbers do you want to enter?  ";
       int len = 0;
       int num = 0;
       cin >> len;
    
       int* array = new int[len];
    
       for ( int i = 0; i < len; ++i )
       {
          cout << "Enter a number:  ";
          cin >> num;
          array[i] = num;
       }
    
       delete [] array;
       return 0;
    }
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

  4. #4
    Registered User
    Join Date
    Nov 2009
    Posts
    82
    I think you answered your own question. Just being able to do the two things you mentioned causes a *significant improvement on performance, especially if the data sets / arrays your working with grow or are already large.

    That is valuable, very practical, and useful, etc.

    All of the possible benefits of pointers should be immediately clear actually, especially if you truly understand its use.

    In memory everything exists in either the size of a byte, or larger. And pointers have a constant size, where dynamic data types grows in to arbitrary size. That relationship exposes the value of a pointer immediately.

    The only other uses for references and pointers are made clear when you understand functions and methods themselves better, for example being able to set and pass callback functions through methods. It's not so common for beginners to write software which incorporates those concepts, but even as a beginner you should stop thinking you are a 'beginner' and on principle inhibit yourself.

    Think in terms of, 'I have this problem, and I need to solve it.' Do what it takes, learn how to do the things required to do what it takes.

    Some of the coolest uses of pointers are simply not 'beginner' by nature, most of their benefits come from making more efficient what would be 'heavier' and more complex. These things would be more obvious if people altered their state of mind in programming from 'working with syntax' to 'implementing mathematics.' Just IMO.
    Last edited by since; 11-13-2009 at 08:28 AM.

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    7,317
    >> Can anyone give me a VERY simple application where pointers are necessary?

    Note that in both examples so far, the pointer isn't necessary in C++. Both have arguably better solutions without pointers (references in the first case and vectors in the second). But the point is still valid.

  6. #6
    Registered User
    Join Date
    Nov 2009
    Posts
    2
    A pointer is a variable that can be given memory locations as values. They're used implicitly in Java and explicitly in C/C++.

    For example, in Java,
    Code:
    String s = new String()
    creates a new String object somewhere and assingns the location of that String object to s.

    The equivalent in C++ is,
    Code:
    std::string* s = new std::string()
    .

    Why do we need them? We need them because they imlpement indirection. We need indirection to handle dyanmic loading of code (usefull for drivers), implementation of virtual functions in C++, traversing data structures, ... the list is almost endless.

  7. #7
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Quote Originally Posted by Daved View Post
    >> Can anyone give me a VERY simple application where pointers are necessary?

    Note that in both examples so far, the pointer isn't necessary in C++. Both have arguably better solutions without pointers (references in the first case and vectors in the second). But the point is still valid.
    And obviously vectors use pointers internally, so C++ still needs pointers to make vectors, strings and most of the STL work properly.
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

  8. #8
    Professional Chef leeor_net's Avatar
    Join Date
    Apr 2004
    Location
    Charles Town, WV
    Posts
    147
    It's hard to give an example of what makes pointers so useful without getting into some form of a lengthy discussion but I'll try to keep it brief.

    I am assuming that you're learning C++ because you want to be able to program games. If that is the case, here's a very simple reason why you want pointers/references:

    If you have an object that handles utility functions... like a Filesystem, a Renderer or a Mixer, you don't want to be constructing new copies of these objects. Instead, you want to be able to quickly access the functions you need and be done with it. These are sometimes called Singletons.

    There are two general ways in which you can do this -- either create global copies of these objects (this defeats the purpose of an OOP language like C++ or Java) or pass a reference to said object.

    Another reason why you want to use pointers and references is in the case of creating a new object within a function. You could create the object in the function and return it by value... which would work except that you'd end up creating two copies of the object. One within the function and one again if you returned it from the function (the local copy within the function goes out of scope when the function returns and so the original object is destroyed).

    For very simple objects this may not be an issue but the second you start handling larger objects, more complex objects or many objects at a time you quickly run into efficiency issues.

    Instead, you can create an object on the Heap and then pass back a reference to that object. Problem solved.

    The final case is when you're dealing with polymorphism and virtual functions. That's a discussion for an entire book so I'll leave it as sometimes you want one object to behave as another. The only way you can do that is with a pointer, a reference or with type casting and casting should generally be avoided unless you know exactly what you're doing.

    It's hard to see it now but believe me when you start getting into complex object heirarchies and you move away from the use of global variables you begin to see why pointers are so useful.
    Last edited by leeor_net; 11-14-2009 at 06:57 PM.
    - Leeor

  9. #9
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Portugal
    Posts
    7,403
    Quote Originally Posted by rodrigorules View Post
    But what are their practical uses for a learning programmer like myself?
    You will need a pointer only when you need to refer to a memory location and can't use a reference for some reason. Under C++, the maxim concerning pointers is "use them only when you must. Not when you can".

    So the general idea is you should avoid pointers until you must indeed use one because there's no reasonable alternative. And yet, you will be using pointers quite often under C++ (go figure). Sometimes even when you are not looking, like the this pointer that you will learn about when you start studying classes under C++.

    - The one most common reason for preferring a pointer over a reference is the so-called reseating. When you need to assign your reference to a different object, you should use a pointer instead. References cannot be reassigned once they have been defined.

    - Probably next in common reasons comes the ability to use null has a valid reference. You cannot assign null to a reference. But you can to a pointer.

    - Also pretty high in the list of common reasons is simply the fact the objects or built-in types you are using may implement pointers as part of their semantics; An array type is very tightly bound to the idea of a pointer. Meanwhile many members of the String class will invite you to work with pointers one way or another.
    The programmer’s wife tells him: “Run to the store and pick up a loaf of bread. If they have eggs, get a dozen.”
    The programmer comes home with 12 loaves of bread.


    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  10. #10
    Malum in se abachler's Avatar
    Join Date
    Apr 2007
    Posts
    3,189
    Once you get into more complex application, you will find that different parts of your program need to access the same data objects. This cannot be done if you are making a deep copy of the object to pass to each thread, but passing a pointer allows each thread or section of code to access the same physical copy of the object. And in real world applications, 'faster' often means the difference between running in real time or not at all. Particularly in my field (machine vision), it is simply not feasible to make copies of the video data for every new call, it would very quickly turn a real time application into something that doesn't complete in my lifetime. It may not seem like much of a savings when as a new programmer you are working with objects that are maybe 100 bytes in size, but when you start dealing with objects that are hundreds of megabytes its just not acceptable to copy that much data when a method typically only accesses a very small subset of the data. e.g. say I want to run a feature detector on an 8x8 section of a frame. By passing a pointer I can do some quick pointer math and extract only that 8x8 image from any arbitrary location in the image. Now say I want to run 192 concurrent threads to process 192 separate 8x8 sections, I cant make 192 new copies of a 100MB image, not only because of memory constraints, but because copying the image 192 times would bring the system to a standstill and in the end I still need to extract only the 8x8 section i am processing in each thread, so making a deep copy would be pointless and a waste of resources.

    And that is just with static objects, some objects may be active, i.e. have threads running that are class based. So makign a copy of the object will not duplicate those threads and any local variables they my use.
    Last edited by abachler; 11-14-2009 at 08:44 PM.
    Until you can build a working general purpose reprogrammable computer out of basic components from radio shack, you are not fit to call yourself a programmer in my presence. This is cwhizard, signing off.

  11. #11
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,406

    Big ole objects

    An object of 100mb? Madre mia! I reiterate my original point, dont create big copies from call stack, but for us non professional coders could you expand on the existence of such behemoths with any typical descriptions or example apps?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sorting number
    By Leslie in forum C Programming
    Replies: 8
    Last Post: 05-20-2009, 04:23 AM
  2. Arrays, pointers and strings
    By Apropos in forum C++ Programming
    Replies: 12
    Last Post: 03-21-2005, 10:25 PM
  3. 2D Array of Pointers
    By Slavakion in forum C++ Programming
    Replies: 12
    Last Post: 03-31-2004, 04:05 PM
  4. Passing pointers between functions
    By heygirls_uk in forum C Programming
    Replies: 5
    Last Post: 01-09-2004, 05:58 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21