Why pointers? (The answer)

This is a discussion on Why pointers? (The answer) within the C++ Programming forums, part of the General Programming Boards category; I am actually speaking from the point of view from someone who used to think pointers were useless. They are ...

  1. #1
    Teenage Mutant Ninja Nerd MMD_Lynx's Avatar
    Join Date
    Aug 2004
    Posts
    65

    Why pointers? (The answer)

    I am actually speaking from the point of view from someone who used to think pointers were useless. They are most definately not. If you don't understand them, you have to learn, because you cannot get past the title of "Newbie" until you do.

    For those of you who do not understand how pointers work, i'll try to explain.

    Code:
    #include <iostream.h>
    
    int main(void)
    {
       int *ptr; //this creates a pointer to an integer (int). The * means it's a pointer. the actual data type is: int *
       int x = 0;
       ptr = &x; //sets the pointer to the address of x.
       cout<<"stored in ptr is: "<<ptr<<endl;
       cout<<"stored in x is: "<<x<<endl;
       cout<<"stored in *ptr is: "<<*ptr<<endl; //by using * you dereference the pointer.
       *ptr = 5;
       cout<<"*ptr set to: "<<*ptr<<endl;
       cout<<"x is now: "<<x<<endl;
       return 0;
    }
    I hope that clears up somethings. Feel free to ask questions or add to what I've said. I am not a C++ guru, but I figured other people may have the same question I did: Why do we need to learn pointers?

    I know I didn't cover everything, but I hope this will inspire some people to help the newbs learn more about pointers.
    Stupid people are useful. You can make them do all the mindless tasks you are too lazy to do yourself.

    Sphynx cats are just bald and wrinkly, like old people, and we don't reject them.

  2. #2
    unleashed alphaoide's Avatar
    Join Date
    Sep 2003
    Posts
    696
    Well, you haven't really answered the question "Why pointers?"
    source: compsci textbooks, cboard.cprogramming.com, world wide web, common sense

  3. #3
    Teenage Mutant Ninja Nerd MMD_Lynx's Avatar
    Join Date
    Aug 2004
    Posts
    65
    yah I was thinking that. there are so many reasons that I didn't want to list them all.
    here are some:
    1. To alter a variables value in a function you have to pass it's address, or a pointer to it.
    2. By passing a pointer to a struct/class/union you avoid placing a lot of variables on the stack. You just pass the address.
    3. You use them when you want to access the value in a variable that could change throughout the program.

    gah, it's harder to explain their uses than I thought it would be. A little help would be appreciated
    Stupid people are useful. You can make them do all the mindless tasks you are too lazy to do yourself.

    Sphynx cats are just bald and wrinkly, like old people, and we don't reject them.

  4. #4
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,088
    Those three situations could all be accomplished using references, and in the general case I prefer using references.

    Some times when I prefer a pointer include:
    1. When storing the address of a variable and the address might be null, or you might have to change what it is pointing to later on.
    2. When storing base class objects in a container to take advantage of polymorphism. References cannot be assigned, so they don't work with many types of containers.
    3. When keeping track of dynamically allocated memory - since new returns a pointer and delete requires one.

  5. #5
    Teenage Mutant Ninja Nerd MMD_Lynx's Avatar
    Join Date
    Aug 2004
    Posts
    65
    Well, I learned C before C++. I don't know much about references. I started looking at them online, and they appear sort of odd to me.
    Stupid people are useful. You can make them do all the mindless tasks you are too lazy to do yourself.

    Sphynx cats are just bald and wrinkly, like old people, and we don't reject them.

  6. #6
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    Some more reasons:
    -In case you want to have an OPTIONAL parameter, you can pass NULL to signal that it's not used
    -If you're returning dynamically allocated memory
    -If you want to use dynamic arrays
    -Can sometimes be helpful in traversing arrays or parsing blocks of data
    -If you don't know how to use them, you won't be able to read anybody else's code

    **EDIT**
    References are like pointers, except easier to handle. While with pointers you need to use * to get the value pointed to, with a reference you just use the name of the reference and it automatically fetches the value for you. The only problem, is you can't point a reference in another direction. Once it's pointing somewhere, it's stuck for good They're particularly useful in passing objects of structures to functions, because then you don't have to worry about creating a copy constructor or anything - like using a pointer.

    **EDIT2**
    Reminded by someone's post below, I thought of a couple more uses for pointers:
    -Good for storing structures in STL containers (don't need to worrry about copy constructors etc)
    -Useful for calling overridden virtual functions in a derived class from a pointer to the base class (polymorphism stuff).
    Last edited by Hunter2; 09-01-2004 at 01:58 PM.
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  7. #7
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    I think of references as either an alias for an object, or if I want to get a little more technical---as a const pointer (that is, can't change what address/object it points to, but can change the value stored at the address/of the object) with some restrictions (as previously pointed out) in return for which there is an easier to use syntax.

  8. #8
    Registered User
    Join Date
    Jan 2003
    Posts
    311
    We use pointers for the same reason we use pronouns, it would suck to have to list every single person by name every time you wanted to say "everyone". C/C++ differs from many languages in that it's pointers are "anything" pronouns, written in your machines native toung. References are prounouns written in the compilers native toung. For the record, polymorphism works just fine with references consider
    Code:
    template<class T>
    std::ostream & pvec(const std::vector<T> &v, std::ostream &os) {
        os << '{';
        std::vector<T>::const_iterator i = v.begin();
        if(i != v.end()) {
            os << ' '<< *i;
            for(++i; i != v.end(); ++i) os << ", " << *i;
        }
        return os << '}';
    }
    
    int main() {
        std::vector<int> v;
        std::ostringstream oss;
        std::ofstream of;
    ...
        pvec(v,oss);
        pvec(v,of) << '\n';
        pvec(v,std::cout) << std::endl;
    ...
    }

  9. #9
    Teenage Mutant Ninja Nerd MMD_Lynx's Avatar
    Join Date
    Aug 2004
    Posts
    65
    i got confused about references. but Hunter kind of cleared it up.
    While with pointers you need to use * to get the value pointed to, with a reference you just use the name of the reference and it automatically fetches the value for you.
    i was thinking, "wouldn't it return the address or something? not the actual value?"
    Stupid people are useful. You can make them do all the mindless tasks you are too lazy to do yourself.

    Sphynx cats are just bald and wrinkly, like old people, and we don't reject them.

  10. #10
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903
    Let us not forget linked lists.. heavily pointer dependant and very optimal.. especially when it comes to binary search trees and stuff
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

  11. #11
    S Sang-drax's Avatar
    Join Date
    May 2002
    Location
    Göteborg, Sweden
    Posts
    2,072

    Three steps

    There are three steps in learning C++:
    1. You think that pointers are hard to understand and seem unneccesary.
    2. You finally understand pointers and what they are for. You can now allocate and deallocate memory dynamically. Pointers make programming easier!
    3. Finally, you realize that pointers don't need to be used much in C++. You use references to pass values to functions and STL containers to dynamically allocate memory. Your code is easy to read and very robust.


    I've seen pointers overused in many, many situations. For great examples, look at any code written by Bjarne Stroustrup.
    Last edited by Sang-drax; 09-02-2004 at 05:20 AM.
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

  12. #12
    S Sang-drax's Avatar
    Join Date
    May 2002
    Location
    Göteborg, Sweden
    Posts
    2,072

    Example of the three steps

    Consider the program that prompts the user to input some number and calculate something with those numbers:

    Programmer at step 1:
    Code:
    cout << "How many numbers do you want:";
    int n;
    cin >> n;
    int numbers[1000];
    for (int i=0; i<n; ++i)
    cin >> numbers[i];
     
    calculate(numbers,n);
    Programmer at step 2:
    Code:
    cout << "How many numbers do you want:";
    int n;
    cin >> n;
    int* numbers = new int[n];
    for (int i=0; i<n; ++i)
    cin >> numbers[i];
     
    calculate(numbers,n);
     
    delete[] n;
    Programmer at step 3:
    Code:
    cout << "How many numbers do you want:";
    int n;
    cin >> n;
    vector<int> numbers(n);
    for (int i=0; i<n; ++i)
    cin >> numbers[i];
     
    calculate(numbers,n);
    Perhaps you think that the last two are equally good, but they are not! There is a potential memory leak if you forget to delete[] the memory you allocated.
    If you think it is extremly easy to remember such a thing, remember that error handling in C++ is done via exceptions, what happens if calculate() throws an exception? The level 3 example handles this, the level 2 does not.
    Last edited by Sang-drax; 09-02-2004 at 02:34 PM. Reason: Hunter2 found my missing star
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

  13. #13
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,812
    Dude, What the heck are these pointer things you are talking about? are they a code that draws an index finger pointing at an image?
    Woop?

  14. #14
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    The three steps rephrased:
    1) You don't think pointers really have a point
    2) You finally get the point of pointers and love them for their pointiness!
    3) You realize that pointers really don't have a point after all

    >>int numbers = new int[n];
    You mean int *numbers?
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  15. #15
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Quote Originally Posted by Sang-drax
    There are three steps in learning C++:
    1. You think that pointers are hard to understand and seem unneccesary.
    2. You finally understand pointers and what they are for. You can now allocate and deallocate memory dynamically. Pointers make programming easier!
    3. Finally, you realize that pointers don't need to be used much in C++. You use references to pass values to functions and STL containers to dynamically allocate memory. Your code is easy to read and very robust.


    I've seen pointers overused in many, many situations. For great examples, look at any code written by Bjarne Stroustrup.
    Have you read his book yet Sang-drax? He explains why he uses pointers instead of references so much. Basically he has said that in his belief that passing a reference should be used only to minimize the amount of data passed to a function that won't change the reference's data. And that a pointer should be used to pass data to a function that might change the data. This is so that when you make the call to a function you'll know if the data being passed in has the possibility of being different after the call.

Page 1 of 4 1234 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  2. delete and delete[]
    By Hunter2 in forum C++ Programming
    Replies: 13
    Last Post: 06-26-2003, 05:40 AM
  3. Pointers on pointers to pointers please...
    By Morgan in forum C Programming
    Replies: 2
    Last Post: 05-16-2003, 12:24 PM
  4. Staticly Bound Member Function Pointers
    By Polymorphic OOP in forum C++ Programming
    Replies: 29
    Last Post: 11-28-2002, 01:18 PM
  5. Pointers pointers pointers....
    By G'n'R in forum C Programming
    Replies: 11
    Last Post: 11-02-2001, 02:02 AM

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