Previous: 6.3 Returning to the Payroll Task with Pointers
Up: 6 Pointers
Next: 6.5 Summary
Previous Page: 6.3 Returning to the Payroll Task with Pointers
Next Page: 6.5 Summary

6.4 Common Errors

  1. Using an uninitialized pointer. Remember, declaring a pointer variable simply allocates a cell that can hold a pointer - it does not place a value in the cell. So, for example, a code fragment like:
    {  int * iptr;
    

    *iptr = 2; . . . }

    will attempt to place the value, 2, in the cell pointed to by iptr; however, iptr has not been initialized, so some garbage value will be used as the address of there to place the value. On some systems this may result in an attempt to access an illegal address, and a memory violation. Avoid this error by remembering to initialize all pointer variables before they are used.

  2. Instead of using a pointer to an object, a pointer to a pointer is used. Consider a function, read_int(). It reads an integer and stores it where its argument points. The correct version is:
    void read_int(int * pn)
         {
              scanf("%d", pn);
         }
    pn is a pointer to the object where the integer is to be stored. When passing the argument to scanf(), we pass the pointer, pn, NOT &pn.

  3. Confusion between the address of operator and the dereference operator.
    ... calling_func(...)
         {    int x;
              called_func(*x);         /* should be &x   */
              ...
         }
         ... called_func(int &px)      /* should be * px */
         {
              ...
         }
    A useful mnemonic aid is that the ``address of'' operator is the ``and'' symbol, & --- both start with letter, a.



Previous: 6.3 Returning to the Payroll Task with Pointers
Up: 6 Pointers
Next: 6.5 Summary
Previous Page: 6.3 Returning to the Payroll Task with Pointers
Next Page: 6.5 Summary

tep@wiliki.eng.hawaii.edu
Wed Aug 17 08:45:54 HST 1994