This blog is under construction

Wednesday, 25 December 2013

Pointer to integer

How to declare integer pointer?
Below is the declaration for pointer to integer.
int *ptr;
Here, ptr is a pointer of type int.

What is integer pointer?
Pointer is nothing but referece to a memory location.  If a pointer is of type integer, then it is called integer pointer.  Usually, integer pointer holds the address of interger variable.
int num = 10, *ptr;
ptr = #
Here, ptr is an integer pointer and it hold the address of the integer variable num.

Accessing array elements using pointers:
Consider the following example,
int arr[5] = {10, 20, 30, 40, 50};
int *ptr;
ptr = arr;
Here, ptr is a pointer to an array of integer.  And it holds the address of the first element in the integer array arr.  Let us see how to access array elements using pointers
*ptr is 10
*(ptr + 1) is 20
*(ptr + 2) is 30
*(ptr + 3) is 40
*(ptr + 4) is 50


Example c program on integer pointers:


  #include <stdio.h>
  int main() {
        int i, num = 10, *ptr;
        int arr[] = {10, 20, 30, 40, 50};

        /* assigning address of the integer variable */
        ptr = &num;
        printf("num: %d\t*ptr: %d\n", num, *ptr);
        /* adding 10 to the value referred by ptr */
        *ptr = *ptr + 10;
        printf("Current value of num: %d\n", num);

        /* assigning address of the 1st element of the arrary to ptr */
        ptr = arr;

        /* accessing array elements using pointers */
        for (i = 0; i < 5; i++) {
                printf("arr[%d]: %d\n", i, arr[i]);
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~$ ./a.out
  num: 10 *ptr: 10
  Current value of num: 20
  arr[0]: 10
  arr[1]: 20
  arr[2]: 30
  arr[3]: 40
  arr[4]: 50


No comments:

Post a Comment