Pointer Expressions


Pointers can be used in expressions.  Basically, pointers are preceded by indirection operator(*).  Consider the following example

int a = 10;
int *ptr1, **ptr2;
ptr1 = &a;
ptr2 = &ptr1;

          a
+---------------+
|       10        |
+---------------+
Addr of a(&a)
  
&a           -> address of a
*(&a)       -> value of a
ptr1         -> address of a
*(&ptr1)   -> address of a
*ptr1        -> value of a
ptr2         -> address of ptr1
*(&ptr2)   -> address of ptr1
*ptr2       -> value of ptr1/address of a
**ptr2      -> value of a

  #include <stdio.h>
  int main() {
        int a = 10, *ptr1, **ptr2;
        ptr1 = &a;
        ptr2 = &ptr1;
        printf("Address of a => &a       : 0x%x\n", &a);
        printf("Value of a   => *(&a)    : %d\n", *(&a));
        printf("Value of a   => *ptr1    : %d\n", *ptr1);
        printf("Address of a => ptr1     : 0x%x\n", ptr1);
        printf("Address of a => *(&ptr1) : 0x%x\n", *(&ptr1));
        printf("Addr of ptr1 => &ptr1    : 0x%x\n", &ptr1);
        printf("Addr of ptr1 => ptr2     : 0x%x\n", ptr2);
        printf("Addr of ptr1 => *(&ptr2) : 0x%x\n", *(&ptr2));
        printf("Val of ptr1  => *ptr2    : 0x%x\n", *ptr2);
        printf("Value of a   => **ptr2   : %d\n", **ptr2);
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/cpgms/pointers/posts$ ./a.out
  Address of a => &a          : 0xbfe29b6c
  Value of a   => *(&a)        : 10
  Value of a   => *ptr1        : 10
  Address of a => ptr1        : 0xbfe29b6c
  Address of a => *(&ptr1)  : 0xbfe29b6c
  Addr of ptr1 => &ptr1      : 0xbfe29b68
  Addr of ptr1 => ptr2        : 0xbfe29b68
  Addr of ptr1 => *(&ptr2)  : 0xbfe29b68
  Val of ptr1  => *ptr2        : 0xbfe29b6c
  Value of a   => **ptr2       : 10

Let us try to use pointers in expressions.  Consider the following
int a = 10, b = 20, sum, product;
int ptr1, ptr2;
ptr1 = &a, ptr2 = &b;

sum = *ptr1 + *ptr2;
*ptr1 is 10
*ptr2 is 20
So, the value of sum is 30

The above expression can also be written as follows
sum = (*ptr1) + (*ptr2);

product = *ptr1 * *ptr2;
Here, the value of product is 200

The above expression can also be written as follows
product = (*ptr1)*(*ptr2);
product = *ptr1**ptr2;
product = * ptr1 * * ptr2;

*ptr1++ -> advances the reference of pointer ptr1
++*ptr1 -> increments value referred by ptr1 by 1

++*ptr1 is equivalent to (*ptr1)++
++*ptr1 is equivalent to ++(*ptr1)

The above expression can also be written as follows
*ptr1 = *ptr1 + 1;
*ptr1 + = 1;

*ptr1--  => decrements the reference of pointer ptr1
--*ptr1  => decrements value referred by ptr1 by 1

The above expressions can also be written as follows
*ptr = *ptr - 1;
*ptr -= 1;

Comments

Popular posts from this blog

Operators And Separators In C Language Operators in C Language:

Difference between asterisk and ampersand operators in c