Pointers and Arrays


Pointers

  • A pointer is a variable that holds an address.
  • A pointer can store addresses from the stack, heap, or read-only memory.
  • Pointers hold the address of only one memory location. However, often the memory location is one element in an array. Therefore, pointers can be used to access arrays.

  • Declarations:
    int *iptr; Creates a pointer to an int named iptr
    char *cptr; Creates a pointer to a char named cptr
    float *fptr; Creates a pointer to a float named fptr
    int **pptr; Creates a pointer to a pointer to an int named pptr

    These declarations create pointer variables on the stack that hold arbitrary values. They are not currently holding usable addresses.

  • Assignments:
    iptr=(int *)malloc (5*sizeof(int)); Allocates 20 bytes on the heap and stores the address in iptr
    cptr="hello"; Creates a string in read-only memory and stores the address in cptr

    float pi=3.14;
    fptr = π Stores the address of pi in fptr
    pptr = &iptr; Stores the address of iptr in pptr

  • Usage
    1. * has two pointer-related functions:
      1. * is used in the creation of pointer variables (above).
      2. * is used to get the value stored at the pointer's address. Getting the value that the pointer points to is called dereferencing the pointer.

    2. *iptr = 5; Sets the value of the location pointed to by iptr to 5.
      int i = *iptr; Sets i to the value pointed to by iptr.
      *(iptr+1) = 10; Sets the value of the second element in the iptr array to iptr to 10.
      iptr[2] = 15; Sets the value of the third element in the iptr array to iptr to 15.

  • Notes
    • Array and pointer notation are interchangeable: *(array+2) means array[2].
    • Unlike arrays, pointers can be assigned to point to new locations. Arrays cannot be assigned to new addresses.
    • & is the opposite of *. & gets the address of a variable. * gets the value pointed to by the address.