Pointers Programs
Pointers Programs
}
11) WAP to traverse a string using pointer
#include<stdio.h>
int main()
{
char *g="C Programming";
int length=0,i=0;
while(*g!='\0')
{
printf("%c",*g);//Value at address
g++;//Pointer is incremented by 1 after each iteration
length++;//Variable for counting length
}
printf("\nLength of the string is:%d",length);
return 0;
}
12) WAP to demonstrate wild pointer
#include<stdio.h>
int main()
{
int *ptr;//Wild pointer
int a=10;
//printf("%x",ptr);//Gives gargage address value
//printf("\n%d",*ptr);//Gives garbage value stored in the grabage address
ptr=&a;//Now ptr is not a wild pointer
printf("\n%d",*ptr);//
return 0;
}
13) WAP to demonstrate NULL pointer
#include<stdio.h>
int main()
{
int *ptr=NULL;
int a=10;
printf("%x",ptr);
//printf("%d",*ptr);//---Not allowed(Dereferencing NULL pointer)
ptr=&a;
printf("\n%d",*ptr);
return 0;
}
14) WAP to demonstrate generic pointer(or void pointer)
#include<stdio.h>
int main()
{
int x=10;
char ch='A';
void *gp;
gp=&x;
printf("\n Generic pointer points to the integer value=%d",*(int*)gp);
gp=&ch;
printf("\n Generic pointer now points to the character %c",*(char*)gp);
return 0;
}
15) WAP to demonstrate dangling pointer
// Deallocating a memory pointed by ptr causes dangling pointer
#include <stdlib.h>
#include <stdio.h>
int main()
{
int *ptr = (int *)malloc(sizeof(int));
// After below free call, ptr becomes a
// dangling pointer
printf("%u",ptr);
free(ptr);
printf("\n%u",ptr);//dangling pointer
// No more a dangling pointer(Solution)
// ptr = NULL;
}
16) WAP to demonstrate constant pointer
#include<stdio.h>
int main()
{
int var1 = 60, var2 = 0;
int *const ptr = &var1;
//ptr = &var2;
printf("%d\n", *ptr);
return 0;
}
Practice questions to do:
WAP to implement insertion and deletion using pointer to an array concept
WAP to find simple interest using pointers
WAP to implement binary search using pointer to an array concept
WAP to check whether the entered integer is prime or composite after passing
pointer to function
WAP to display largest of three numbers using pointers
WAP to display smallest of three numbers after returning pointer from function
WAP to calculate area of triangle using pointers
WAP to check whether the entered number is palindrome or not using pointers
WAP to display the sum of odd array elements after passing array to a function using
pointer
WAP to swap the values of two variables using pointers
WAP to count vowels in a given string using pointer