Pointer and Array

Standard Input/Output
  • Arrays

    • Array
      • Is used to store similar data items
      • In contiguous memory locations
      • Under a single name (a variable)
      • It uses index (subscript) to access to its element
      • Index starts from 0 and increases 1 every element
    • Array addressing is relative addressing
      • Array subscripting notation is converted to pointer notation during compilation
      • So writing array subscripting using pointer notation can save compile time
      • E.g., a[0] is the same as *a; a[1] is the same as *(a+1)
  • Pointers

    • Pointer addressing is absolute addressing
      • Exact location of the elements can be accessed directly by assigning the starting location of the array to the pointer variable
      • The pointer variable is incremented to find next element
      • C treats the name of the array as it is the pointer to the first element
      • It uses index (subscript) to access to its element
  • Assign array to pointer

    • Array is declared and pointer variable can point to the starting location of an array
    • Array elements can then be accessed using pointer variable
    • General form
      • pointer_var = &array_name[0];
      • OR
      • pointer_var = array_name;
  • PointerAndArray Source Code

    /*

     * File:   main.c

     * Author: phamvanvung

     *

     * Created on September 21, 2014, 7:01 PM

     */

     

    #include <stdio.h>

    #include <stdlib.h>

     

    /*

     *

     */

    int main(int argc, char** argv) {

        int a[] = {2, 3, 4};

        printf("Address of the first element of array is: %d\n", &a[0]);

        printf("Value stored inside a is: %d\n", a);

        printf("Access to the first element of array using its index: a[0] = %d\n", a[0]);

        printf("Access to the first element of array using pointer: *a = %d\n", *a);

        printf("Access to the second element of array using its index: a[1] = %d\n", a[1]);

        printf("Access to the second element of array using pointer *(a+1) = %d\n", a[1]);

        printf("Access to the third element of array using its index: a[2] = %d\n", a[1]);

        printf("Access to the third element of array using pointer *(a+2) = %d\n", a[1]);

        return (EXIT_SUCCESS);

    }