Total Pageviews

Saturday 5 May 2012

Pointers


Pointers
Pointer are a fundamental part of C. If you cannot use pointers properly then you have basically lost all the power and flexibility that C allows. The secret to C is in its use of pointers.

C uses pointers a lot. Why?:
  • It is the only way to express some computations.
  • It produces compact and efficient code.
  • It provides a very powerful tool.

C uses pointers explicitly with:
  • Arrays,
  • Structures,
  • Functions.
NOTE: Pointers are perhaps the most difficult part of C to understand. C's implementation is slightly different DIFFERENT from other languages.
 
What is a Pointer?
A pointer is a variable which contains the address in memory of another variable. We can have a pointer to any variable type.

The unary or monadic operator & gives the ``address of a variable''.

The indirection or dereference operator * gives the ``contents of an object pointed to by a pointer''.

To declare a pointer to a variable do:
int *pointer;

NOTE: We must associate a pointer to a particular type: You can't assign the address of a short int to a long int, for instance.


Consider the effect of the following code:

       int x = 1, y = 2;
       int *ip;
       ip = &x;
       y = *ip;
       x = ip;
       *ip = 3;

It is worth considering what is going on at the machine level in memory to fully understand how pointer work. Consider Fig. 9.1. Assume for the sake of this discussion that variable x resides at memory location 100, y at 200 and ip at 1000.

Note A pointer is a variable and thus its values need to be stored somewhere. It is the nature of the pointers value that is new.

1 comment:

  1. These courses enable you to become more learned and informed for all the minute factors.

    MBA Notifications 2012

    ReplyDelete