Use of A Pointer
Use of A Pointer
Use of A Pointer
Program to demonstrate the use of ampersand operator which returns the address of a
variable.
#include <stdio.h>
int main()
{
int x; // The program returns different addresses in different run time.//
// Prints address of x
printf("%p", &x);
return 0;
}
Program to demonstrate the use of asterisk operator (To access the value in the address)
#include <stdio.h>
int main()
{
// A normal integer variable
int Var = 10;
// This prints 20
printf("After doing *ptr = 20, *ptr is %d\n", *ptr);
return 0;
}
OUTPUT
Pointer Expressions and Arithmetic
A pointer can be
Incremented and decremented
Added and Subtracted
Note: Pointer arithmetic is meaningless unless performed on an array.
1. Pointer Addition
It is perfectly legal if we add an integer variable with a pointer.
Explanation:
int main(){
printf("\nDifference : %d",ptr2-ptr1);
return 0;
}
Output:
Difference : 250
ptr2 - ptr1 = (2000 - 1000) / sizeof(float)
= 1000 / 4
= 250
Subtraction of two numbers using pointers
#include<stdio.h>
void main()
{
int num1,num2,sub,*p1,*p2;
printf("Enter 1st number: ");
scanf("%d",&num1);
printf("Enter 2nd number: ");
scanf("%d",&num2);
p1=&num1;
p2=&num2;
sub=*p1-*p2;
printf("\n\nDifference of %d and %d is %d",*p1,*p2,sub);
}
Output:
// Driver program
int main()
{
// Declare an array
int v[3] = {10, 100, 200};
An array name acts like a pointer constant. The value of this pointer constant is the address of the
first element. For example, if we have an array named val then val and &val[0] can be used
interchangeably.
Program
#include <bits/stdc++.h>
using namespace std;
void geeks()
{
// Declare an array
int val[3] = { 5, 10, 20 };
return;
}
// Driver program
int main()
{
geeks();
return 0;
}
Output:
Pointer is a variable that holds the memory address of another variable. The first pointer is used
to store the address of second pointer. That is why they are also known as double pointers.
Example:
int main()
{
int var = 789;
return 0;
}