Sort of, but thinking of pointers as numbers can lead to some dangerous
misconceptions. A pointer value is a location in memory. On some
systems, such a location is represented by a number, or something that
looks very much like a number, but the C language doesn't assume such a
representation.
You're right, I tend to think in implementation-specic terms instead of
the formal language definition. Bad habit.
Thanks for clarifying.
Yes, you can perform arithmetic on pointers, but only in limited ways.
If memory serves, the only defined arithmetic operations on pointers are:
- test if a pointer is (not) NULL
- compare two pointers (to see if they point to the same object)
- subtract two pointers (yields an integer result of ptrdiff_t)
- add or subtract an integer value to a pointer (only for non-void*
Think about a street address, like "1600 Pennsylvania Avenue". It
includes a number, 1600, but the address as a whole certainly isn't a
number.
On most implementations I have seen, pointers are represented by
hexadecimal numbers, usually with 8 or 12 digits. But you're right,
the language makes no assumptions about what form pointers
take and it would be bad habit for a programmer to do so.
Right. Most systems will trap in some way on attempts to dereference a
null pointer, but the language doesn't guarantee it; instead, it merely
says the behavior is undefined.
At the very least, it may avoid specific kinds of bug exploits.
I see applications dump core on null pointer dereferences every once
in a while in my job as a sysadmin. Usually memory-hungry applications
that probably don't check the returned result of malloc() properly.
On the other hand, setting a pointer to NULL does give it a value that
can safely be examined.
I actually forgot to write down that part, it also helps with debugging
as your debugger can check for null pointers.