What is a Pointer?
“A pointer is a variable which contains the address in memory of another variable“.
The unary or monadic operator & gives the “address of a variable”.
The indirection or dereference operator * gives the “contents of an object pointed to by a pointer”.
int var; // declaration of “Integer type” variable name var which will have some // address in memory
int *ptr; // To declare a pointer to a variable do
ptr = &var; // copying address of variable “var” into new variable “ptr”
as I have shown in below example,
// C program to demonstrate use of * for pointers in C
#include <stdio.h>
int main()
{
// A normal integer variable
int var = 10;
// A pointer variable that holds address of var.
int *ptr = &var;
// This line prints value at address stored in ptr.
// Value stored is value of variable “var”
printf(“Value of var = %d\n”, *ptr);
// The output of this line may be different in different
// runs even on same machine.
printf(“Address of var = %p\n”, ptr);
// We can also use ptr as lvalue (Left hand
// side of assignment)
*ptr = 20; // Value at address is now 20
// This prints 20
printf(“After doing *ptr = 20, *ptr is %d\n”, *ptr);
// lets check value of var
printf(“Value of var = %d \n”,var);
return 0;
}
// A normal integer variable
int var = 10;
// A pointer variable that holds address of var.
int *ptr = &var;
// We can also use ptr as lvalue (Left hand
// side of assignment)
*ptr = 20; // Value at address is now 20
so, in above lines var is contenting 10 and address of var is assigned to ptr and as ptr is address of var so if change value at address will, change also as shown in above example.