Saturday, July 26, 2008

Basic Stuff in Pointer (part-1):

Pointer is not a tough one to learn, but it is rather easy when you understand the basic stuffs involved in the pointer.

There are six things you need to know to learn the basic stuffs in pointer

Understanding the variables and computer memory:

What will happen when we declare a variable?

Compiler determines what kind of variable it is. Based on the type of variable it reserves a memory. It is very simple to understand with an example.

EG: We are going to buy a chocolate. There are varieties of chocolate with different cost. Some of them are costly and cheaper. What we will do based on our finance we buy chocolate. If we are having 10 rupees we buy chocolate for ten rupees. If we have 50 rupees we buy chocolate for 50 rupees.

Similarly if the variable type is a char it reserves one byte, if it is int 2 bytes and goes on based on the type it allocates memory in computer.

The compiler knows 4 things about a variable

  • Its name
  • Its type
  • Its size
  • Its location in memory

E.g.: int a; compiler allocates 4008344 as memory location.

Then’ a’ is variable name
‘a’ is int (Integer) type
‘a’ is 2 byte size
‘a’ is located at 400834 in memory.

Using Size of:

We can determine the size of a variable by Sizeof () operator. Actually sizeof is a function which returns the sizeof a variable.

E.g.: program demonstrating use of sizeof ()
Int a;
printf (“The size of variable 'a' is %d”, sizeof (a));
Result:
The size of variable ‘a’ is 2

Finding memory location with & operator

& is an operator when prefixed with a variable, it returns the location (address) of the variable.
That is why & is prefixed with a variable in name in scanf.

E.g.:
Int a;
Scanf(“%d”,&a);
If we enter 4 as input it scans 4 and saves in the location of a allocated by compiler. To know what the address is we are using & in scanf before variable name.

We can see other three thing s in the next post:

Creating pointer variables
Storing memory locations in pointer
Doing pointer math

No comments: