C Pointers


Simple Examples

    #include <stdio.h>

    /* Code illustrating simple pointers */

    main()
    {
      char c1 = 'A';    /* Creates space for c1 & initializes it */
      char c2 = 'B';    /* Creates space for c2 & initializes it */
      char c3 = 'C';    /* Creates space for c3 & initializes it */
      char c4 = 'D';    /* Creates space for c4 & initializes it */
      int i = 13;       /* Creates space for i & initializes it */
      int j;            /* Creates space for j */
      double d;         /* Creates space for d */

      char * charPtr;   /* Creates space for charPtr */
      int * intPtr;     /* Creates space for intPtr */
      int * intPtr2;    /* Creates space for intPtr2 */
      double * dPtr;    /* Creates space for dPtr */
              /* NOTE: all pointers are the same size */

      j = i;            /* j & i both have 13 (two copies) */
      j = 42;           /* j now has 42; i unchanged */
      intPtr = &i;      /* intPtr now points to i */
      intPtr2 = &i;     /* intPtr2 also now points to i */
              /* NOTE: two pointers, both pointing to same memory */

      *intPtr2 = 26;    /* intPtr2 unchanged; what it points to is changed */

      intPtr2 = &j;     /* intPtr2 now points to j */

      printf ("i: %d; *intPtr: %d; *intPtr2: %d\n", i, *intPtr, *intPtr2);

    }


Alyce Brady, Kalamazoo College