Thursday, 3 December 2015

Pointer in C Programming

Pointer in C Programming Language

Prepared By : Hitesh Vataliya

Pointer is a reference variable which stores address of another variable inside it.
Pointer variable occupies only 2 bytes of memory for storing address of any type of variable like int, char, float or double. Because pointer variable only stores address of same type of data which the pointer variable have, and for storing address it only needs two bytes of memory.
Pointer is flexible to use with character array as well as we can access multidimensional array with pointer variable easily which is called array of pointers.

Here 1 example is given
 int a =10;
int *p;
p=&a;

in above example a is int type variable which stores 10 inside it.
*p is pointer variable.
p stores address of int type variable a.
*p having the value of a.

Programming Exercises of Pointer 


1. Write a program to show the use of pointer[ change the content stored inside variable a using pointer p].


void main()
{
int a=10;
int *p;
clrscr();
p=&a;
printf("\n\t\tThe value of a is %d and address is %d",a,&a);
printf("\n\t\tThe value of *p is %d and p is %d",*p,p);
*p=20;
printf("\n\t\tThe value of a is %d and address is %d",a,&a);
printf("\n\t\tThe value of *p is %d and p is %d",*p,p);
getch();
}

Output : The value of a will be changed to 20 instead of 10 at the end of the program with pointer variable p.



2. Write a program for swap two variables value using call by reference. [use pointer variables as parameter]


#include<stdio.h>
#include<conio.h>
void swap(int *n1,int *n2)
{
int *temp;
*temp=*n1;
*n1=*n2;
*n2=*temp;
}
void main()
{
int a=10;
int b=111;
clrscr();
printf("\n\t\tThe value of a is %d and b is %d",a,b);
swap(&a,&b); //call by reference
printf("\n\t\tThe value of a is %d and b is %d",a,b);
getch();
}


Output : swap function changes the values of a and b return to the main function, we can get two values return into the main function from called function with the help of pointers only.


3. Write a program to access character array using pointer.

Scale Factor is the difference of memory address from going one memory address to another inside the array. Here the array is of character type and hence it's Scale Factor is 1.

#include<stdio.h>
#include<conio.h>
void main()
{
char name[30]="Vataliya Tuition Classes";
char *p;
int i;
clrscr();
p=&name[0];
for(i=0;i<strlen(name);i++)
{
printf("%c",*p);
p++;
}
getch();
}

Output : Here the Scale Factor is 1. If The array type is float then Scale Factor will be 4.

If You wants to learn C Programming Language For BCA, MCA, Diploma, Degree Engineering (BE), ME, Then Visit : VATALIYA TUITION CLASSES.

FINAL YEAR PROJECT TRAINING

PHP PROJECT TRAINING

JAVA PROJECT TRAINING 

ASP.NET PROJECT TRAINING

IGNOU BCA/MCA

NIELIT O LEVEL/A LEVEL/B LEVEL/C LEVEL

GTU DIPLOMA/BE/ME IN COMPUTERS/IT

No comments:

Post a Comment