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

C++ Pointers doubt

  1. Jul 28, 2006 #1
    Can anyone help me understand the basic use of pointers.
    I am aware of pointers,yet I feel that a program can be made more
    easier without using a pointer.

    My basic dout is that can pointers be used to save memory by dynamic declaration of variables.
    I thought over it but found that using ptr in programs of my level is useless.

    I have just begun with programming and not yet started with classes,ie OOP.
    Could anyone suggest me some good programs.
  2. jcsd
  3. Jul 28, 2006 #2


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Many programs can indeed be written without pointers.

    There are only a few instances where pointers become "necessary" for reasons of efficiency:

    1) When you need to refer to the same large piece of data in many different places in the code.

    2) When you need to allocate memory dynamically, and you don't know a priori what the address of that memory will be.

    - Warren
  4. Jul 28, 2006 #3
    Can you give me an example where I need to use pointer
    Just the example without any code.
  5. Jul 28, 2006 #4
    from my experiance these few instances occure quite often.

    for example - binary trees, they are very important.. search bsp trees, for game use.
    and linked lists are a necessity in database hendling...
    Last edited: Jul 28, 2006
  6. Jul 28, 2006 #5
    Coding most data structures where the # of objects is large and varies constantly. Also if your structs/classes are large in memory and you only want one instance of the object but many such objects and have many manipulations to do on those objects like in Graph Theory Or anything that uses graph theory like neural nets. Another example is from fargoth about games, eg player or agent/ai entities...infact all entities in a game.
  7. Jul 28, 2006 #6
    Yeah your correct in that pointers can make allocating memory more efficient, because you can decide at runtime what size a given field/variable needs to be rather than allocating a chunk at compile time. This is really something thats important in larger projects, but for simple low performance applications you can do without, however if your learning ( say from a text and practicing some programs ) then its really a good idea to get used to using them effectivley rather than opting for the easier route.
  8. Jul 28, 2006 #7
    The main reason beginners find pointers so difficult is that their use is more abstract than lets say the use of an array. Their very abstract nature though gives the user great power. For instance, one could set a pointer to a memory location within a hardware register (assuming the OS will let you). Then you can pass that pointer down a chain of functions. Each of the functions will then have access to that register through the abstration of the pointer. The functions don't even need to know what the pointer is pointing at or anything about it.

    Some languages such as Java don't have pointers. Java was made to be called by web pages. As such, pointers would allow hackers to create programs that could access your computer memories. This is dangerous so the designers of the language simply left it out. This reduces the power of the language, but gives it the safety needed to create applets.
  9. Jul 29, 2006 #8


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member


    The reason Java lacks pointers is because everything in the language is passed by reference. The designers of the language chose this approach because it makes programming easier and less prone to error.

    Passing by reference is a higher-level, abstracted form of using a pointer. There are many ways to protect memory access even with the use of pointers, and all modern operating systems use such protection.

    - Warren
  10. Jul 29, 2006 #9
    From my experience with pointers, it creates alot of problems when you dont know how to handle them properly..... ie. dangling pointers and so on. And passing by reference in JAVA works alot better for me and is easier to understand.........each to their own i suppose...
  11. Jul 29, 2006 #10
    I also doubt one more yhing that while declaring a pointer we allocate a memory location i.e we allocate the same amount of memory as the one to which yhe pointer points .
    So this means that we initially allocate memory for the pointer then again go for dynamic declaration of another variable.

    so if suppose we are utilising more memory than we are supposed to.
    Please correct me if i am going wrong anywhere in my logic.
  12. Jul 29, 2006 #11


    User Avatar

    Staff: Mentor

    Also note that the C++ standard library provides container objects that allow the programmer to avoid using raw pointers in many situations that would otherwise require them.

    For example, in C and in C-style programming in C++, when you don't know the required size of an array at compile time, you have to allocate it dynamically. Also if you want to change the size of an array while the program is running, you have to allocate it dynamically. Instead of that, in C++ you can use the 'vector' data type which behaves sort of like a simple array that you can resize by using a member function. It actually implements this internally using a dynamically allocated array, but it hides all the pointer management from you, and you never deal with the pointer directly (it's "private" to the vector).

    Similarly, the 'string' data type allows you to dispense with char*.

    There's also a 'list' container which basically encapsulates a doubly-linked list (with forward and backward pointers), a 'map' container which usually uses a tree structure internally, etc.
  13. Jul 29, 2006 #12
    I am now clear that we can save memory by dynamic allocation of memory by the example of array declaration.

    I would like to know more about 'vector' data type .
    Can you please send me a link or suggest any source to get more knowledge on C++.
    Last edited: Jul 29, 2006
  14. Jul 29, 2006 #13


    User Avatar

    Staff: Mentor

    I can't help you with online sources because I'm more comfortable with using books to learn a subject as complex and as structured as programming. For people who already know a bit about programming, I highly recommend "Accelerated C++" by Koenig and Moo. It's a thoroughly modern treatment of C++ that uses vectors instead of arrays, strings instead of char*, etc. I also recommend it to people who know quite a bit of C++ already, but haven't worked much with the containers in the standard library.

    Most other C++ books and tutorials show you the "old fashioned" way to do things first. By the time you get to the nifty things in the standard library, which aren't really that hard to use, you've formed habits that are hard to break.

    Here's a quick sample of what vectors can do:

    Code (Text):

    //  This is a quick demonstration of the 'vector' data type, showing
    //  a couple of reasons why it's nicer than a plain old array.

    #include <iostream>
    #include <string>
    #include <vector>

    using namespace std;

    int main ()
    // Create this vector with a specific size and fill each slot
    // individually.

       vector<string> myStrings(7);

       myStrings[0] = "Hi";
       myStrings[1] = "I";
       myStrings[2] = "am";
       myStrings[3] = "a";
       myStrings[4] = "vector";
       myStrings[5] = "of";
       myStrings[6] = "strings";

    // Display the contents of the vector.  Note that a vector can tell you
    // how big it is, so you don't have to keep track of the size (7)
    // separately.

       for (int k = 0; k < myStrings.size(); ++k)
          cout << "String #" << k << ": " << myStrings[k] << endl;

    // Create this vector with initial size zero, and let it grow to
    // accommodate the data

       vector<string> moreStrings;

       cout << "Enter a series of strings, one per line;\n"
            << "enter an empty line to finish:" << endl;

    // Read strings one at a time.  They can contain spaces because
    // we're reading line by line using getline().

       string newString;
       while (getline (cin, newString) && newString != "")
          //  Append each new string to the end of the vector.
          //  The vector automatically grows to accommodate the data.

          moreStrings.push_back (newString);

    // Display the contents of the vector.  As we are writing this program,
    // we don't know how big the vector will be at this point, but
    // the vector can tell us its current size anyway.

       for (int k = 0; k < moreStrings.size(); ++k)
          cout << "String #" << k << ": " << moreStrings[k] << endl;

       return 0;
    I've tested this program, so you should be able to just copy and paste and compile and run it.

    Homework: try to rewrite this program using arrays and pointers instead of vectors, and char* instead of strings, while still allowing the user to enter any number of strings, of any length!
    Last edited: Jul 29, 2006
  15. Jul 29, 2006 #14
    scorpion: search in google for STL(standard template library)...i would give you the google site but my computer is having problems, nvm here is the list


    Does Java have the problem of passing in the entire variable(by reference not by copy) through the parameter list of a function? Does reference variables declared in the code-body work in Java same way it does in C++, that is you can only initialize it only once(CType &x; x=y; //where y defined somewhere else, and x cannot equal anything else)...if so then i can see this as an advantage for C++, because if your searching for an object in an array(eg. nearest neighbour) you can store by pointer without having to copy all the values of that class. If Java doesn't allow ptrs then you would have to copy the class(unless of courses the reference usage isn't the same as in C++).
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook