Pointer Program
Pointer Program
About Pointer
• C Pointer is a variable that stores/points the address of another
variable. C Pointer is used to allocate memory dynamically i.e. at run
time. The pointer variable might be belonging to any of the data type
such as int, float, char, double, short etc.
• Syntax : data_type *var_name;
• Example : int *p; char *p;
• Where, * is used to denote that “p” is pointer variable and not a
normal variable
KEY POINTS TO REMEMBER ABOUT POINTERS IN C
• Normal variable stores the value whereas pointer variable stores the address of
the variable.
• The content of the C pointer always be a whole number i.e. address.
• Always C pointer is initialized to null, i.e. int *p = null.
• The value of null pointer is 0.
• & symbol is used to get the address of the variable.
• * symbol is used to get the value of the variable that the pointer is pointing to.
• If pointer is assigned to NULL, it means it is pointing to nothing.
• Two pointers can be subtracted to know how many elements are available
between these two pointers.
• But, Pointer addition, multiplication, division are not allowed.
• The size of any pointer is 2 byte (for 16 bit compiler).
EXAMPLE PROGRAM FOR
POINTER IN C
#include <stdio.h>
void main()
{
int *ptr, q;
q = 50;
ptr = &q;
printf(“%d”, *ptr);
}
Output:
50
C program to add two numbers using pointers
#include <stdio.h>
void main()
{
int first, second, *p, *q, sum;
printf("Enter two integers to add\n");
scanf("%d%d", &first, &second);
p = &first;
q = &second;
sum = *p + *q;
printf("Sum of entered numbers = %d\n",sum);
}
C program to add numbers using call by reference
#include <stdio.h>
int add(int *, int *);
void main()
{
int first, second, *p, *q, sum;
printf("Input two integers to add\n");
scanf("%d%d", &first, &second);
sum = add(&first, &second);
printf("(%d) + (%d) = (%d)\n", first, second, sum);
}
int add(int *p, int *q)
{
Output:
int sum; Input two integers to add
sum = *p + *q; 10
20
return sum;
10+20=30
}
Sum of array elements using
pointers
#include<stdio.h>
void main()
{
int array[5];
int i,sum=0;
int *ptr;
printf("\nEnter array elements (5 integer values):");
for(i=0;i<5;i++)
scanf("%d",&array[i]);
ptr = &array;
for(i=0;i<5;i++)
{ Output:
sum = sum + *ptr; Enter array elements (5 integer values): 1 2 3 4 5
The sum is: 15
ptr++;
}
printf("\nThe sum is: %d",sum);
}