10 Pointer
10 Pointer
Pointers
p 5000 5048
Concept of Address and Pointers
int *a;
float *b;
char *c;
Pointer Declaration
⚫ When is * used?
#include<stdio.h>
main()
{
char a='A';
int id=44;
float gpa=3.87;
}
Use of &
⚫ &j; /* valid
⚫ &arr[i]; /* Valid
⚫ &289; /* Invalid
⚫ &(x+y); /* Invalid
Accessing of Pointer variable
#include<stdio.h>
main()
{
int x,*y,z;
x=1;
y=&x;
z=*y;
printf("value of x is %d \n",x);
printf("value of y is %u \n",y);
printf("value of z is %d \n",z);
printf("value of *y is %d \n",*y);
printf("value of *&x is %d \n",*&x);
}
Illustration of pointer assignments
#include<stdio.h>
main()
{
int x,y,*z;
x=44;
y=40;
z=&x;
printf("x=%d\t y=%d\t z=%u\n", x, y, z);
y=*z;
*z=10;
} The ouput is
Illustration of pointer assignments
Declaration x y z
X = 44; y = 44 40
40;
address 2293416 …………… …………….
…
Z= &x 44 40 2293416
address 2293416 …………… …………….
…
Y = *z 44 44 2293416
address 2293416 …………… …………….
…
*z = 10 10 44 2293416
address 2293416 …………… …………….
…
Illustration of pointer assignments
#include<stdio.h>
main()
{
int x,y,*z;
x=44;
y=40;
z=&x;
printf("x=%d\t y=%d\t z=%u\n", x, y, z);
*z=10;
y=*z;
#include<stdio.h>
void main()
{
int a=5;
int *pa;
int **ppa;
pa=&a;
ppa=&pa;
printf(“Address of a =%u\n",&a);
printf(“value of pa= Address of a =%u\n",pa);
printf(“value of *pa= value of a =%u\n",*pa);
}
Pointers and Arrays
Program 5:
#include<stdio.h>
int main()
{
int i,*r,odd[5]={1,3,5,7,9};
r=odd;
for(i=0;i<5;i++)
{
printf("%d\n",*r);
r++;
}
return 0;
}
Program to sum of all elements stored in an array
Program 6:
#include<stdio.h>
int main()
{
int i,*r,odd[5]={1,3,5,7,9},sum=0;
r=odd;
for(i=0;i<5;i++)
{
sum=sum+*r;
r++;
}
printf(“total=%d”,sum);
return 0;
}
Pointer and character strings
Program 8:
#include<stdio.h>
void main()
{
char *name;
int length;
name=“GOOD”;
char *cptr=name;
printf(“%s\n”,name);
while(*cptr!=‘\0’)
{
printf(“ %c stored in address %u ”,*cptr, cptr);
cptr++;
}
length= cptr-name;
printf(“Length=%d”,length);
}
Swap Function
⚫ The following shows the swap function modified from a "call by value"
to a "call by reference". Note that the values are now actually
swapped when the control is returned to main function.
Category 5: Functions that return multiple values.
#include<stdio.h>
func(int x, int y, int *ps, int *pd, int *pp);
void main()
{
int a, b, sum, diff, prod;
a=6; b=4;
func(a, b, &sum, &diff, &prod);
printf(“sum= %d difference=%d product=%d”, sum, diff, prod);
}
func(int x, int y, int *sum, int *diff, int *prod)
{
*sum = x+y;
*diff = x- y;
*prod = x*y;
}
Factorial program in c using pointers
findFactorial(num,&factorial);
printf("Factorial of %d is: %d",num,factorial);
return 0;
}
Find the largest Number in c using pointers
#include <stdio.h>
void main()
{
int a, b, large;
printf("Enter two numbers to find the larger: ");
scanf("%d%d",&a,&b);
larger(a, b, &large);
printf("%d is larger",large);
}