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
{ 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.
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.
... 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.