How to change value stored in variable using pointer

We all know that pointer is a variable that store the address of another variable and pointer variable itself has an address in memory.


 int n = 5;

We declare and initialize pointer as

int *ptr  //declaration of pointer

ptr = &n  //initialization of pointer variable. Here n is an integer variable.

We can write something like

*ptr = 24;

It means the value stored at the memory location which is stored in pointer variable ptr will be 24. The value of n will be 24. See the following example.

#include<stdio.h>
int main()
{
 int n = 5; //Declaration and initialization of variable n
 int *ptr; //Declaration of pointer variable ptr
 ptr = &n;//Initialization of ptr
 
 printf("Value of n = %d\n",n);
 
 *ptr = 45;
 
 printf("Value of n = %d",n);
 
 return 0;
}


We can not do as

ptr = n        //WRONG
*ptr = &n   //WRONG
ptr = 6       //WRONG
n = ptr      //Not Wrong because address of n will be a value.




Popular posts from this blog