Friday, August 27, 2010

POINTERS !!

POINTERS

Pointers can used with arithmetical relational, logical and assignment expression. these are not directly used with arithmetical relational, logical and assignment expression only these values are used.

POINTER DECLARATION
The declaration of a pointer variable takes the following form:
Data_type *pt_name;
The above statement tells the compiler three things about the variable pt_name.
  1. The asterisk(*) tells that the variable pt_name is a pointer variable.
  2. Pt_name needs a memory location.
  3. Pt_name points to a variable of type data type.

POINTER EXPRESSION
Like other variables, pointer variables can be used in expressions. Arithmetic and comparison operations can be performed on the pointers.

Pointer arithmetic:
C allow us to add integers from pointers as well as subtract one pointer from another.
Sum+=*p2

Addition of a number to a pointer
Int i=4,*j,*k;
J=&I;
J=j+1;
K=j+3;

Subtraction of a number from a pointer
Int i=4,*j,*k;
J=&I;
J=j-2;
J=j-5;
k=j-6;

POINTERS AND ARRAYS

When an array is declared, the compiler allocates a base address and sufficient amount of storage to contain all the elements of the array in contiguous memory locations.
The array declared as:
Static int x[5]={1,2,3,4,5};

Is store as follows:
Elements           x[0]    x[1]     x[2]     x[3]       x[4]
Values                1        2          3         4           5
Address           1000    1002   1004   1006   1008

DYNAMIC MEMORY ALLOCATION
C allocates desire amount of memory to variables and arrays defined in a program on the memory stack. In some cases the exact amount of memory is not known at the compile time and memory must be allocated only at runtime. runtime memory allocation is known as dynamic memory allocation.

POINTER AND FUNCTION
Pointers as function arguments occur with its address cell.
That is in this function is called by using address of variable. It is also called call by reference. In call by reference the address of actual arguments is passed to the function.
e.g. main()
{
Int x;
X=20;
Change (&x);
Printf(“%d”,x);
}
Change (p)
Int *p;
{
*p=*p+10;
}

POINTER TO POINTERS
Pointer is a variable that hold the address of another variable this concept can be further extended we can have a variable that hold an address of a variable that in tern holds an address variable. this type of variable will be known as pointer to pointer variable.
Example:-
Main()
{
Int i=10,*p;
Int **ptr;
p=&I;
ptr=&p;
Printf(“the value of I is %d”,*p);
Printf(“value of p is %u”,**ptr);
}

No comments:

Post a Comment