Welcome Guest   Login   Mar 28, 2017
Tutorials
C
HTML
Java
Chapter-7
Pointers

Pointer is a memory variable that holds the address of another variable, which is called pointing to variable. Using the pointer variable the contents of the variable to which it is pointing can be accessed directly & also can be changed. Pointers are declared using the * as prefix operator.

Int *ptr;

the address of other variables can be assigned using & prefix operator.

int i=30;

ptr=&i;
 

Here is the program to explain the same.
 
main()

{

int x=30;

int *ptr;

ptr=&x;

printf("\n x=%d",x);

printf("\n &x=%u",&x);

printf("\n ptr=%u",ptr);

printf("\n *ptr=%d",*ptr);

}


 

values of the variable can be modified to which the pointer is pointing.
 
main()

{

int x=30;

int *ptrx=&x;

printf("\n before assignment x = %d",x);

*ptrx=20;

printf("\n After assignment x = %d",x);

}

The datatype of the pointer is not to specify the type of data pointer will be storing but to specify to what datatype it will point in future. All the pointer variables are of unsigned int type.
 
main()
{

int *iptr;

float *fptr;

char *cptr;

printf("\nSize of integer pointer is %d",sizeof(iptr));

printf("\n Size of float pointer is %d",sizeof(fptr));

printf("\n Size of char pointer is %d",sizeof(cptr));

}


 

The above program shows though the pointers are of different types, still all of them occupy the same space in memory i.e. 2 bytes. This proves that datatype of pointer is not to decide what pointer is storing but to what it is pointing.
 
 

Call by reference

While we were learning User Defined functions we have done an example on call by value, Here comes a method Call by Reference which is related to that topic.
main()
{
int x=20,y=30;
printf("\n In main Function x = %d, y=%d",x,y);
swap(&x,&y);
printf("\n In main Function x = %d, y=%d",x,y);
}

swap(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
printf("\n In swap Function x = %d, y=%d",*x,*y);
}

Here in this example instead of passing values of variables we are passing the addresses of variables and they are stored in pointer variables in function swap. Swap function uses these address and modifies the contents of variables to which its pointing. So through pointers we can change the contents of variables for swap purpose.
 
 

Other Topics that can be done with pointers are like
( To maintain the syllabus concise & Simple these topics are not explained here).

  • Pointers and Arrays.
  • Pointer to pointer
  • Dynamic Memory Allocation
  • Direct Access to MS-DOS memory location

My New Blog

My Award winning Whitepaper

Contradicting Light
My Personal Blog


Trace Mobile Location



My Book Reviews
 




Tech Jokes Worth Reading
 
Top
Home
www.deepjava.com 1999-2014 (C) Developed and maintained by D-Kay Consultancy