Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C/++/# Usefulness of Pointers in C++?

  1. Mar 9, 2017 #1
    Hey everyone,

    I'm currently going over a chapter on pointers for my 2nd programming course (no prior experience outside of class). I'm wondering what the usefulness of pointers is, other than if you need direct access to the memory location of a variable.

    The text essentially says it's good for dynamically allocating memory for arrays that you don't know the size of. However, every example they've given so far, I am able to code another way without pointers. And it makes the code way easier to follow (in my opinion).

    The only thing that I can think of is that it could potentially increase the efficiency of the code since you can delete the pointer when you're done with it and re-create it when you need it. However, isn't this essentially the same as a local variable just with a little more flexibility?

    Currently it just seems like a more surefire way to end up with errors.
     
  2. jcsd
  3. Mar 9, 2017 #2

    berkeman

    User Avatar

    Staff: Mentor

    Take a look at Linked Lists. That's one place where pointers make a lot of sense, IMO.
     
  4. Mar 9, 2017 #3

    rcgldr

    User Avatar
    Homework Helper

    In the case of C, you can use something like int *ptr2array = malloc(count * sizeof(int) ) to allocate a large array from the heap. If you have an array of objects that you need to sort, it may be faster to create an array of pointers to objects and sort the array of pointers. The objects could be lines of text from a file read into memory as a single block of memory.
     
  5. Mar 9, 2017 #4

    nsaspook

    User Avatar
    Science Advisor

    A pointer is a variable containing the address of another variable. Pointers allow you to refer to the same space in memory from multiple locations (they're not copies of a variable) and each of the locations could have a different representation (data structures) of the memory in that same space. You can also have function pointers where the variable contains the address of a program function can be executed via the function pointer.

    "It's easier to give someone an address to your home than to give a copy of your home to everyone." so everything actually uses pointers but C/C++ just exposes them to the programmer rather than hiding them.

    "surefire way to end up with errors"
    Yes, If you don't know exactly why you're using pointers, you shouldn't use them.
     
  6. Mar 9, 2017 #5

    jedishrfu

    Staff: Mentor

    One thing about C/C++ pointers are that they are datatype oriented.

    By that I mean a char pointer when incrementing it will add one causing the pointer the reference the next byte whereas an int pointer will increment by two bytes (for 16-bit ints) and a double pointer will increment by 8 bytes...

    Here's some more info on pointers which are everywhere in C/C++ and are actually favored over array indexing in many cases.

    https://www.tutorialspoint.com/cprogramming/c_pointers.htm
     
  7. Mar 9, 2017 #6

    QuantumQuest

    User Avatar
    Gold Member

    I'll talk about pointers in C but the same concepts expand for C++ giving a lot more power, given the existence of objects.

    Essentially, pointers are variables whose values are memory addresses. So, in contrast to a normal variable that contains a specific value, a pointer contains an address of a variable that contains a specific value. So, a pointer indirectly references a value.

    Pointers enable programs to simulate call-by-reference and to create and manipulate dynamic data structures i.e structures that their size is changed at execution time. Such structures are linked lists, queues, stacks and trees. You can't allocate memory beforehand for data structures that will grow or shrink at execution time, without doing dynamic allocation of memory through pointers.

    I'll also give you a reference for the concepts of pointers and their use, "Pointers and Memory" from Stanford CS Education Library by Nick Parlante.
     
  8. Mar 9, 2017 #7

    Mark44

    Staff: Mentor

    If you need to allocate an array whose size isn't known at compile time, you can allocate space on the heap dynamically (i.e., at run time) using malloc(). I'm thinking in terms of C here.

    Sure it's more complicated, but it allows you to do something that you couldn't otherwise do -- determine during a program's run exactly the size of the array you need. Otherwise, using statically declared arrays (arrays declared at compile time), you have to declare the array to be large enough to hold as much data as you think might be needed. This means that much of the time your array will be larger than what you need, wasting memory, and too small if you guessed wrong on the maximum size you need.

    The address is not necessarily another variable. You can have a pointer to a function of a specific type, which is the way qsort() works with its parameter that is a pointer to a comparison function. Or the pointer can hold the address of some location in memory that has no identifier associated with it.

    All true, but a pointer can be cast to a pointer of a different type. Also, most C/C++ compilers these days consider the int type to be 4 bytes, not 2. That change happened along about 1997 or so, causing me some confusion, as I was used to ints being two bytes.
     
  9. Mar 9, 2017 #8

    jtbell

    User Avatar

    Staff: Mentor

    Let me guess... using std::vector?
     
  10. Mar 9, 2017 #9

    jedishrfu

    Staff: Mentor

    Thanks @Mark44 for the update. In 1997 or so was the I jumped on the Java train with version1.1 and havent looked back.
     
  11. Mar 9, 2017 #10

    strangerep

    User Avatar
    Science Advisor

    Heh, I've been using C++ since 1985. (Anyone here remember cfront 1.0?) Anyway, there's an old computer science saying:

    Every software design problem is solved by introducing one more level of indirection.

    When you can understand that, Grasshopper, you will have learned (the relevance of pointers). :wink: :biggrin:
     
  12. Mar 10, 2017 #11
    You have good instincts. Sure pointers can be used to support a lot of use cases, but hardly any of them require the use of raw pointers. And it's the general consensus of the C++ creators and communities that raw pointers should be avoided as much as possible. Like you say, almost all of their use cases can be replaced by safer and more idiomatic C++ alternatives. In fact, most C and C++ programs are plagued by memory leaks and security issues and various bugs because of faulty use of raw pointers. But it's not just memory leaks, improper casting is also a problem. Their use is sometimes a way to get around type safety, or to implement a hackish and potential unsafe or hard to understand way to accomplish something.

    In good idiomatic C++, you can almost virtually eliminate the possibility of memory leaks in the code you have written (no telling about its dependencies) of such problems. I am quite sure no memory leaks have been introduced by my code in the several years since I started writing proper C++ code.

    Of course for certain reused data structures it could be preferable to just use raw pointers rather than the alternative of existing data structures that encapsulate them. But such use cases should ideally be limited to fairly small encapsulated modular classes or structs that are not constantly being modified and which are evaluated by someone compitent. But at the very least, you should limit calls to new only inside a constructor and to always make sure to call delete in the destructor. This both guarantees the memory will be freed when the object goes out of scope, and it eliminates the need to search though your code aimlessly trying to keep track of where things are being allocated and allocated. It would also be good practice to initialize pointers to 0 if you are scattering new and delete all around, since deleting a null pointer won't cause any problem (although if this is happening it's a sign your code is messed up anyways).

    Otherwise the main justifiable use case for pointers is to support polymorphism (inheritance). Of course you can often still use smart pointers. I don't think you shouldn't just go filling a vector with dynamically allocated raw, owning pointers for example.

    At the basic level, choose pass by reference over pass by pointer, choose functors or lambdas over function pointers, choose vectors or smart pointers of other encapsulations/classes over using raw pointers to dynamically allocated objects, and in general whenever you find yourself using a raw pointer, give a second thought about whether it's really the best approach.
     
    Last edited: Mar 10, 2017
  13. Mar 10, 2017 #12

    Mark44

    Staff: Mentor

    Those are good points, but for the OP, who is just starting out, I believe that it's important to understand how pointers work. Whether they should be used in a particular case is a separate issue.
     
  14. Mar 10, 2017 #13
    Pointers are important when you want to have multiple threads or objects all working with the same information. Here is a time that I use pointers extensively: option pools. I often have classes that can work in several different ways, and instead of injecting a single strategy in it, which requires mallocs and frees when changing, I create member objects and create a pointer called m_active, which I simply point to whichever strategy I want.
     
  15. Mar 21, 2017 #14
    Pointer is also usefull for some scabrous trick in template programing, and for inheritance.
     
  16. Mar 21, 2017 #15

    jedishrfu

    Staff: Mentor

  17. Mar 22, 2017 #16
    Scabrous is an english word for risky, dangerous, or complex, it's not the name of a method.
     
  18. Mar 23, 2017 #17
    I think he's referring to something like this.

    Code (C):
    struct parent {
        virtual ~parent(){}
        virtual void step(void){}
    };
    struct child : public parent {
        virtual void step(void){}
    };

    std::vector<parent *> container;
    container.push_back(new parent);
    container.push_back(new child);
    container.push_back(new parent);

    std::vector<parent *>::iterator i = container.begin();
    std::vector<parent *>::iterator e = container.end();
    for (; i != e; ++i){
        if (i -> step == child::step){  //Should always work, but scary code
           std::cout << "Hacky way to check type revealed a child" << std::endl;
        }
    }
    Polymorphic objects have hidden member variables that point to sections of code. These are called the vtable.
     
    Last edited: Mar 23, 2017
  19. Mar 23, 2017 #18
    A very simple example is to make a vector of box to put everything you want inside.

    //Useless Parent
    class parent
    {
    }

    // But Template Child
    template<class T>
    class child : public parent
    {
    public :
    child(T * p):my_class(p){}

    private :
    T * my_class;
    }

    std::vector<parent *> v;
    v.push_back(child(WhatYouWant));
    .....

    This example go against the inheritage principle but can be usefull in some configuration.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: Usefulness of Pointers in C++?
  1. Use of pointers (Replies: 3)

Loading...