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



Pointer operators in C Pointer operators in C Reviewed by Mursal Zheker on Minggu, Desember 29, 2013 Rating: 5

Tidak ada komentar:

Diberdayakan oleh Blogger.