Can you please explain pointers?

why do we need pointers? please explain pointers some specific uses.
-I am a learner
Last edited on
Read from here for the next few pages. It explains what they are, why we need them, how to use them along with nice diagrams. Plus Marshall Brain has a real knack for explaining tricky subjects.
http://computer.howstuffworks.com/c20.htm
pointers (like references) allow a certain kind of "loosening" of strict static typing in C++

in other words, they allow for polymorphism when using OOP in C++

let me illustrate with an example in OOP - suppose we have:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace std;
class P {
  public:
    P() { }
    virtual void printMe() { cerr << "I am P" << endl; }
};
class C1 : public P {
  public:
    C1() : P() { }
    virtual void printMe() { cerr << "I am C1" << endl; }
};
class C2 : public P {
  public:
    C2() : P() { }
    virtual void printMe() { cerr << "I am C2" << endl; }
};
main() {
  C1 arr1[10];  // always prints "I am C1"
  P  arr2[10];  // always prints "I am P"
  C2 arr3[10];  // always prints "I am C2"
  P* arr4[10];
  // insert any address-of-P or address-of-child-of-P in arr4
  arr4[0] = &C1;  // will print "I am C1"
  arr4[1] = &C2;  // will print "I am C2"
  arr4[2] = &P;    // will print "I am P"
  unsigned i, n = 3;
  for ( i=0; i<n; ++i )
    arr4[i]->printMe();
}

Pay attention to Lines 19-21; since you have defined arrays of the actual objects C1, P, and C2, they will always call the method associated with those types when you call printMe().

You will do so strictly because you have told the compiler that you want to allocate arrays specifically memory for those objects to hold those specific objects.

However, Line 22 is special; it says I want an array of pointers to type P (meaning pointers to any object of type P or object of type X where X is a child of P) - so now, when you assign addresses to this array arr4, it will call the appropriate printMe() according to the true type of the object pointed to.

There are other uses for pointers like function pointers are good for callbacks, and const pointers to objects were good for avoiding copy-construction (before the days of references). In essence, any time you want to use indirection or delayed execution, pointers are useful.

Passing pointers or references to functions rather than the actual objects is also crucial in C++.


Last edited on
one other note: I may be wrong, but I think pointers originally existed in C because C is a low level language and pointers are a crucial part of machine and assembly language

if you look at assembly language for CPUs, there are a bunch of commands for addressing and accessing offsets of addresses

pointers is just a slightly higher level representation for the same thing
@kbw http://computer.howstuffworks.com/c26.htm
this page explains what I am looking for.. thanks for your valuable reply....

@kfmfe04

I am leaving off the computer. so I can't study right now... sorry....
Last edited on
That link does explain a form of using pointers in C, however it doesn't exactly answer your question. :)

And I am afraid that sometimes more experienced ones can find complicated ways of explaining simple ideas. (not directed at anyone in particular)

Pointers very simple, but can take awhile to fully understand. They are memory addresses that "point" to data in your computers memory. This gives you a very powerful way to manipulate information. With great power comes great responsibility, in other words, you have the power
to make many mistakes.

Pointer arithmetic as described above is sort of arcane to someone with a non C background. Be prepared to get your 'hands dirty' in the sense that you might have to make application after application before you get all the tricks down.

In short, you should view them as a simple aspect of the language, but respect how profound
that aspect is.
@kfmfe04

I can't understand your code fully....
have you done any OOP or virtual methods yet? if not, revisit this post later...
pointers:

Think of a variable like a home. It has an address, and it holds things. A pointer is basically a forwarding address to the house. So you can access the house by the address that the pointer holds.

</bad analogy>

Now how is this useful in code? There are tons and tons and tons of ways that pointers are useful. one such way is for efficiency. For example:

say we had a function, one that acted on a variable that stored a TON of data. Well if we just pass the variable in like normal, the variable is actually copied for that instance of the function:
1
2
3
4
5
6
7
8
 int addall(BIGVAR bv){
   for (int a = 0; a < bv.size(); a++){
      static int e = 0;  //This is kind of a side lesson, if you make a static variable, it doesn't die
                             //when the scope changes like normal variables do.
      e += bv[a];
   }
   return e;
 }


In the previous function, we actually made a copy of bv. Now this isn't super important when you're just working with variables like int's and char's and such, but say you had a 100 page document stored in a string or a vector<char>, then it get's pretty bad making a deep copy.


Another Reason Pointers Are Awesome(also applies to references, actually mostly references):

Say we had a variable that happened to be Really large, and we want to change small parts of it, with a function or a method. Well without pointers, we'd just say myvar = function(myvar);, which is (AFAIK) making two deep copies of your object. However if you use a pointer, you don't have to copy it ever! you can just say function(myvar);. Now I'm sure that makes no sense to you, so here's an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//Using ints showing the usage of a pointer.
int dbl(int orig){ //Deep copy.
    return orig * 2;
}
void dbl(int* orig){ //Shallow copy.
    (*orig) *= 2; //(*var) is a dereference. or accessing the variable at the address of the pntr.
}

int main(){
    
    int number = 12;
    int othernumber = 12;
    
    ///First, let's double the "number" variable
    number = dbl(number);
    
    //"number" now holds 24.
    ///Now, let's double the "othernumber" variable
    
    
    dbl(&othernumber); 
    
    //This second double is passing in the address of "othernumber" an address and a pointer
    //are close to synonymous. Here's how you would do this with a pointer variable:
    
    int* inptr = &othernumber; //Making a new int pointer, and making it point to "othernumber"
    
    dbl(inptr);
    
    //this third example produces EXACTLY the same results as the other examples.
    //you can access the variable pointed to by a pointer by DEREFERENCING it:
    
    if((*inptr) == othernumber){} //ALWAYS(well maybe not) returns true, 
        //because they are the same! =]
        
}



Of Course
These aren't the only uses of pointers, but they are at least two really useful and cool things you can do with pointers. As you program and come up with more and more complicated programs, you'll learn to love them!

Any Questions?

thank you for all to reply..... I try to fully understand your explanations.... for some more replies I leave it unsolved for now....
Topic archived. No new replies allowed.