This blog is under construction

Wednesday 25 December 2013

Array of pointer to integer

Array of integer pointers in nothing but an array whose elements are pointer to integer.

How to declare array of pointer to integer?
Below is the declaration for array of pointer to integer.
int *arr[10];

Dynamic memory allocation for integer pointers in an array:
Below is the procedure to perform dynamic memory allocation for the integer pointers in an array.
int *arr[3];
for (i = 0; i < 3; i++) {
    // allocate memory block to hold 3 integers
arr[i] = (int *)malloc(sizeof(int) * 3);
}

Example program on array of pointer to integer:
Let us see how to access elements pointed by integer pointers in an array using an example program.


  #include <stdio.h>
  #include <stdlib.h>
  int main() {
        int i, j, k, *arr[3];

        /* dynamic memory allocation for array of int pointers */
        for (i = 0; i < 3; i++) {
                arr[i] = (int *)malloc(sizeof(int) * 3);
        }

        /* assigning values to pointees */
        k = 0;
        for (i = 0; i < 3; i++) {
                for (j = 0; j < 3; j++) {
                        *(arr[i] + j) = k++;
                }
        }

        /* printing the values of pointees */
        for (i = 0; i < 3; i++) {
                for (j = 0; j < 3; j++) {
                        printf("%d ", *(arr[i] + j));
                }
                printf("\n");
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~$ ./a.out
  0  1  2 
  3  4  5 
  6  7  8 


No comments:

Post a Comment