Skip to main content

Pointer operators in C

There are two types of pointer operators.  They are
1. Address operator(&)
2. Indirection operator(*)

Address Operator:
It is used to get the address of the given  variable.  Consider the following,
Example:
int a = 10, *ptr;
ptr = &a;
Here, &a gives us the address of the variable and the same is address to pointer variable ptr.  Address operator is also known as reference operator.

Indirection operator:
It is used to get the value stored in an address.  Consider the following,
Example:
int a = 10, b, *ptr;
ptr = &a;  // referencing(&a)
b = *ptr;  // dereferencing(*ptr)
Here, ptr has the address of the variable a.  On dereferencing the pointer ptr, we will get the value stored at the address of a.

Example C program on pointer operators

  #include <stdio.h>
int main() {
int a = 10, b, *ptr;
ptr = &a; // referencing (&a)
b = *ptr; // dereferencing (*ptr)
printf("Value of &a is 0x%x\n", &a);
printf("Value of ptr is 0x%x\n", ptr);
printf("Value of a is %d\n", a);
printf("Value of b is %d\n", b);
printf("Value of *ptr is %d\n", *ptr);
return 0;
}


  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Value of &a  is 0xbfb1715c
  Value of ptr  is 0xbfb1715c
  Value of a is 10
  Value of b is 10
  Value of *ptr is 10



Comments

Popular posts from this blog

restorecrtmode example in c

Header file:     graphics.h Synopsis:        void restorecrtmode();       Description:       restorecrtmode() restores screen mode to text mode. restorecrtmode function in c graphics   #include <graphics.h>   #include <stdlib.h>   #include <stdio.h>   #include <conio.h>   int main(void) {         /* request auto detection */         int gd = DETECT, gmode, err;         int midx, midy;         /* initialize graphics and local variables */         initgraph(&gd, &gmode, "C:/TURBOC3/BGI");         /* read result of initialization */         err = graphresult();         if (err != grOk) {                 /* an error occurred */               ...