Thread: Pointers

    #1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2002
    Posts
    3
    Rep Power
    0

    Pointers


    I'm learning C++ at university....

    I'm really having problems understanding pointers, my lecturers have said there really useful and showed us how to implement them but that doesn't really help.

    All i want to know is:

    What are they?
    Why do we use them?
    Where would we use them?
    What are the advantages to using a pointer instead of a variable?

    some url's would be nice if anyone has any explaining them
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Oct 2000
    Location
    Back in the real world.
    Posts
    5,966
    Rep Power
    190
    Afaik there is few use for pointers in C++... itīs mainly a C thing. but since you seldomly do "pure C++", you need to learn them anyway...

    What are they?
    they are pointers. a variable that does not contain a value, but contains the address of a another variable in memory.
    Why do we use them?
    one example:
    sometimes you need to have a function modify variables that are out of itīs scope. either you pass them via reference (so you can modify them) or pointer (pointers and references are mostly exchangeable)
    another one:
    you should not (cannot in C) pass arrays and structures to functions. for other languages where you can, it makes your program slow and can quickly overflow your stack.
    ... 100 more reasons to be found out as you get more experience in C
    Where would we use them?
    anywhere you use variables that are already defined in another part of your program.
    What are the advantages to using a pointer instead of a variable?
    no "advantage". hard to answer this. you seldomly use pointers instead of variables. They are not complementary but add up to each other. Again, youīll see with gaining eperience where to use pointers...

    Pointers are hard for beginners, i know. But they are part of what makes C so powerful. Once you understood it, youīll have lots of fun (and also trouble!) with them ;)

    If you want some more "hands-on" examples, i can post some if you request.

    [edit]
    i would like to see other peopleīs oppinions on that too, so please post here, you C gurus out there...
    [/edit]
    Last edited by M.Hirsch; October 8th, 2002 at 01:17 PM.
  4. #3
  5. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2002
    Posts
    3
    Rep Power
    0
    yeah some example would be excellent :)

    I'm doing object oriented programming and OpenGL this semester and i haven't done C++ in ages i need to know and understand pointers :|



    I'm in for some long caffinated nights :)


    However your answer has helped, so instead of me say passing an array like i would in PHP you'd point to the array and pass the pointer to the function instead. Correct?
    Last edited by StuRReaL; October 8th, 2002 at 01:55 PM.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jan 2002
    Location
    Seattle WA
    Posts
    863
    Rep Power
    14
    The basic thing to remember is a pointer is a location (in memory) of another object, not the object itself. The next hurdle is learning what the * operator does in it's various contexts, along with the & operator. Very important, and potentially confusing at first.

    As already mentioned pointers and passing by reference are very closely related. Which you use, sometimes doesn't matter, other times, one method is clearly easier than the other. The main difference between these three functions:
    Code:
    void Function1(int number){number++;} // A 'normal' function.
    void Function2(int* number){*number++;} // Expects a pointer.
    void Function3(int& number){number++;} // Passed by reference.
    Is that when you pass Function1 an integer, a copy of the integer is made for Function1, and Function1 operates only on this copy. The actual integer that is passed to Function1 from the calling function remains unchanged. Function2 and Function3, on the other hand, are not passed copies of the integer, but a pointer or reference. These functions make changes to the integer, and the change will be reflected in scope of the calling function.
    Code:
    int nMyNumber = 0;
    Function1(nMyNumber);
    // nMyNumber is still == 0.
    Function2(&nMyNumber);
    // nMyNumber is now == 1;
    Function3(nMyNumber);
    // nMyNumber is now == 2;
    What pointers allow you to do (or passing by reference) is to allow a function to modify something that isn't in it's scope. Without this ability, functions would be forced to return the objects they modify, which would slow down programs alot since so many copying must be done. Something like:
    Code:
    MyObject = OperateOnObject(MyObject);
    Would be an example. Inefficient, but it will work without pointers or references.

    The most common use for pointers when you're a beginner, I'd say, is to create objects on the heap. These objects are not in the scope of any specific function, so you need to store their location, hence requiring a pointer. Objects are created on the heap with the new operator. Pointers are also crutial to understanding how arrays work.
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Oct 2000
    Location
    Back in the real world.
    Posts
    5,966
    Rep Power
    190
    Another picture:
    you have a struct containing infos about your vhs collection.
    Code:
    typedef struct tape_info {
      char[100] title;
      char[100] director;
      int year;
    }
    and you have a variable that contains a list of this type:
    Code:
    tapes[] tape_info;
    each entry in this array (afaik called "vector" in C) takes about 204 bytes in memory.
    now you make a function to search through all tapes to find all movies by "Steven Spielberg".
    Code:
    tape_info *current;
    current=tapes[0];
    while (current) {
      if ( (*current).director=="Steven Spielberg")
        printf("Movie found: %s", (*current).title);
    }
    and you donīt need more than 4 bytes for your variable.

    remember, C was designed for low-level programming. It is very close to Assembler, where there is no variables but only pointers to memory locations.

    question: Why donīt you make the variable global and have much easier searching using a for-loop?
    answer: because globals are bad style (here) and make your code hard to maintain once it grows.

    other question: why donīt you pass the whole array to the function to search it?
    answer: if you arenīt dealing with vhs tapes where you have little information to process, youīll end up duplicating several 100ks up to megs.

    i cannot make up a situation right now from my head, but there is similar ones where you HAVE to use pointers... hmmm. maybe if you access variables of other programs / modules that you donīt have direct access to...

    annotation: i am no native english speaker, so if you donīt understand what i am saying, could be my fault ;) and i did not use C for quite some time, maybe the brackets are not necessary and i am not 100% sure about the de-reference (and other) syntax...

    [edit]
    sorry, in the above the "==" comparison is wrong. C cannot compare strings like that, it should be:
    if ( strcmp((*current).director, "Steven Spielberg"))
    and the strcmp() function also uses pointers ;) (char *)
    [/edit]
    Last edited by M.Hirsch; October 8th, 2002 at 02:22 PM.
  10. #6
  11. /(bb|[^b]{2})/

    Join Date
    Nov 2001
    Location
    Somewhere in the great unknown
    Posts
    5,163
    Rep Power
    792
    As mentioned before, pointers just point to something.
    Some built-in function require pointers. This is a common theme in C. Not too sure about C++ but I am pretty confident that a large portion of functions require this also.
    The only thing I would actually add would be the dereference in M.Hirsch's example.
    In the case of dealing with the actual stucture variable, you would reference via the . operator. To reference via a pointer use the ->. This is the same reference method used in objects in C++ basically.
    Hence:
    current->director

    Pointers can be difficult to learn at times, especially since it is easy to have a "pointer in the forest" or pointing to an overlapped memory location which will cause problems. This only gets more complicated when you start dealing with pointers to pointers i.e. (**current and ***current). But once you learn it and get some expierence actually using it, but it starts making a lot more sense.
  12. #7
  13. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2002
    Posts
    3
    Rep Power
    0
    thanx guys its becoming a little clearer but i'm going to have a look around to see if i can find some tutorials on them somewhere

    there must be some somewhere
  14. #8
  15. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2002
    Location
    Tallahassee
    Posts
    55
    Rep Power
    14

    Recursive Binary Search(using pointers)


    I am taking a Data Structures class at school and I decided to post this question in this thread because the original author of this thread could not figure out why pointers are so useful. Well, lemme tell ya, if you are in the CS or CEngineering program you will definitely need to know pointers cold.
    With that being said, I was wondering if anybody could solve an algorithm for me. Basically, it is the binary search algorithm that searches in a SORTED array of integers and finds the elements you're looking for. This function returns the position of the element in the array. Here's my pseudocode so far:
    Code:
    //item is the value we're searching for
    //list the actual array, passed in here as a pointer
    //listSize is the size of the array
      int binarySearch(int item, int* list, int listSize){
        if (listSize == 0){
          return -1;
        }
        listSize / 2;
    I know I have less than nothing but if somebody could help me out that would be great. Thanks
  16. #9
  17. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,616
    Rep Power
    4247
    supaben34, why don't you make this a separate thread, either here or in the algorithms forum. That way, it'll make things clearer for people who search these forums later on.

IMN logo majestic logo threadwatch logo seochat tools logo