POINTERS

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
alamit
New poster
Posts: 10
Joined: Mon Jun 05, 2006 12:21 pm

POINTERS

Post by alamit »

I want to learn more about pointers. I can't understand them. Who can tell me how use them in programs?
sumankar
A great helper
Posts: 286
Joined: Tue Mar 25, 2003 8:36 am
Location: calcutta
Contact:

Post by sumankar »

Invest some time in a book depending on your choice of language.
Assuming that you know what variables are here's a start:
pointers are variables -- they hold the address of the pointee.
To get to the pointee we use the dereferecing operator or *.

Code: Select all

/* for some type T, if var is a variable of type T i.e. */
T var; 
/* then we can have a pointer to T as follows */
T *pvar;
/* this is uninitialised & before you can do something
    meaningful aka not shoot yourself in the foot you'd
    intialise it as ... */
    pvar = &var;        /* i.e. pvar now points to var */
/* to get to the value of var via pvar we would do */
    func( *pvar );
/* for some function that takes a parameter of type T func(T var) */
Yes, the same you'd use when multiplying integers or floats or ...
They are kind of special for you can subtract them, add integer
offsets but cannot multiply or add two pointers. Then there is the
scaling when offsets are added to pointers. A pointer to void is
even more special -- it can hold pointers to anything, though you possibly
can't do much when you cannot dereference them. Normally, you
cannot expect integers & pointers to be interchangable (since
not all systems have memory addresses that are just integers)
with the sole exception of 0. Zero again, can never point to a valid
memory location -- so it is also a special value for pointers.

It so happens that pointers and arrays are strongly related: so
you would read it up on favorite textbook as well. Note: array names
decay to pointers almost always --with exceptions such as when it is the
operand of the sizeof operator.

And then comes the qualifiers like const, restrict etc.

Pointers can be very powerful & will likely blow your program off
the first few times ;)
alamit
New poster
Posts: 10
Joined: Mon Jun 05, 2006 12:21 pm

Thanks

Post by alamit »

Thank you :)
Post Reply

Return to “C++”