Tuesday 1 October 2013

Pointers in C

Switch Case                                                                                                                  Function


Pointers :- it is used to access the memory locations and manipulating the address of the variables. Pointer is only thing that creates the big difference between C and the famous language Java , .net .
we use pointers for accessing the memory location.

Operator:-  & called  "ampersand"  or "address of"  , declaring any variable with &  represents address or memory location.

EX:-
main()
{
int a=10;
printf("%d",a);       //print the value of a
printf("%u",&a);    //prints the address of a
}

OUTPUT:-   10  -value
                     268772 -memory address

it simply means "10" store at "268772" memory location named "a". "a" is the name of memory address.


Declaration of Pointer:- * is used for declaring pointer type variable. and if a variable is pointer type and we write *variable name then it directly represents the value at variable name.
mainly it refers the value present at that memory  location.

int *p;  // int type pointer
char *c;  //char type pointer

Simple Program for Pointers:-

main()
{
int a=10;
int *b;
b=&a;
printf("%d",a);
printf("%u",&a);
printf("%x",b);
printf("%x",*b);
}

output:- 10
             268772
              268772
               10

Description:-  * is used for declaring pointer type variables.
first it simply prints the value of "a"
&a   prints the address of the a or memory location.
b =&a   b is a pointer type variable in which we store the address of a. so on printing b it prints the address of a.
*b  it refers to the value at b .simply it prints the value present at that memory locations.

We can also apply arithmetic operations on the pointer like increment \decrement operator,

Ex:-
int *a,*b;
++a;
--a;
a==b;

this simply increment or decrement the address not the values.

Pointers with Arrays:- We can also print the address of the elements of the array by using the pointer.

Ex:-
main()
{
int a[3];
for(int i=0;i<3;i++)
printf("%x",&a[i]);
}

output:-it prints the address. of all 3 elements.


Pointers with Functions:- it is also known as call by reference.passing the address as a argument of the function.

Ex:-
void swap(int *a , int *b);
main()
{
int a=1,b=2;
printf("%d%d",a,b);
swap(&a,&b);
printf("%d%d",a,b);
}
void swap(int *a, int *b)
{
int c;
c=*a;
*a=*b;
*b=c;
}
output:-
1 2
2 1

Description:-in function declaration we define pointer type variable.
in function calling we pass the address of the variable.
 in function definition it takes the value at that address .
simply we transfer the value through their address.
so by this way we can use pointer into the function.

we discuss all the examples on pointers in example section.









No comments :

Post a Comment