All C program code Examples

Pointers In C

// Show Address of Variable using pointer

#include

void main()
{
int a=12;
float b=24.25;
char c=’a’;
clrscr();
printf(“\n Address of A : %u”,&a);
printf(“\n Address of B : %u”,&b);
printf(“\n Address of C : %u”,&c);
getch();
}

Output:
Address of A : 65524
Address of B : 65520
Address of C : 65519

// Show Actual value and Address of Actual value

#include

void main()
{
int a=23;
int *p;

p=&a;
printf(“Address of a : %u”,&a);
printf(“\nAddress of p : %u”,p);
printf(“\nValue of a : %d”,a);
printf(“\nValue of *p : %u”,*p);
getch();
}

Output:
Address of a : 65524
Address of p : 65524
Value of a : 23
Value of *p : 23

// Swapping using pointer

#include

void main()
{
int a,b;
int *x,*y,t;

printf(“Enter the value:”);
scanf(“%d%d”,&a,&b);
printf(“\n\n”);
x=&a;
y=&b;
t=*y;
*y=*x;
*x=t;
printf(“x:%d\nY:%d”,*x,*y);
getch();
}

Output:
Enter the value:85 96
x=96
Y=85

// Pass by Value in Pointer Example

#include

void square( int );

int main ()
{
int a = 20;

square( a );

printf( “\n a = %d”, a );

return 0;
}

void square( int x )
{
x = x * x;
printf( “\n x = %d”, x );
}

Output:

x = 400
a = 20

// Pass by Reference in Pointer Example

#include

void square( int* );

int main ()
{
int a = 10;

square( &a );

printf( “\n a = %d”, a );

getch();
return 0;
}

void square( int *pa )
{
*pa = *pa * *pa;
printf( “\n *pa = %d”, *pa );
}

Output:

*pa = 100
a = 100

// Addition operation on Pointer

#include

void main()
{
int p;
int *ptr;

ptr=&p;
printf(“enter value:”);
scanf(“%d”,ptr);
*ptr=*ptr+5;
printf(“\n value of p is:%d”,p);
printf(“\n value of *ptr :%d”,*ptr);

}

Output:
enter value:5
value of p is:10
value of *ptr :10

// Value store using pointer

#include

void main()
{
int *p,a[10],i;

p=&a[10];
printf(“Enter The value:>>\n”);
for(i=0;i<5;i++,p++)
{
scanf(“%d”,&*p);
}
p=p-1;
for(i=0;i>
85 63
96 2
54 54
2 96
63 85

// Null Pointer Example

#include

int main ()
{
int *ptr = NULL;

printf(“The value of ptr is : %x\n”, ptr );

return 0;
}

Output:

The value of ptr is : 0

/*Calculate length of string using pointer*/

#include
void main()
{
char str1[20],*p1;
int i,len=0;
printf(“Enter string: “);
scanf(“%s”,&str1);
p1=&str1;
while(*p1!=’\0′)
{
p1++;
len++;
}
printf(“Length of String : %d”,len);

}

Output:
Enter string: C Example
Length of String : 9

/*Area and Perimeter of Rectangle using pointer*/

#include
void rectangle(int a, int b, int * area, int * perim);
void main()
{
int x, y;
int area, perim;
printf(“Enter two values separated by space: ” );
scanf(“%d %d”, &x, &y);
rectangle(x, y, &area, &perim);
printf(“Area is %d Perimeter is %d\n”, area, perim);
}
void rectangle(int a, int b, int * area,int * perim)
{
*area = a * b;
*perim = 2 * (a + b);
}

Output:
Enter two values separated by space: 10 20
Area is 200 Perimeter is 60