[Ilugc] C doubt involving pointers

  • From: binand@xxxxxxxxx (Binand Sethumadhavan)
  • Date: Wed May 18 17:51:44 2005

On 18/05/05, Mohammed Riyaz <p_mdriyaz@xxxxxxxxxxx> wrote:

dosent make any sense to me. isint (type *)0 a null pointer??  so how is
it possible to offset mem, when we dont even have a structure there??

You have to keep in mind two things.

1. Data structures exist only in the brain of the programmer. As far
as the computer is concerned, it is all a stream of bits (logically
ordered into bytes).

2. A pointer is a memory address. As with any kind of sequential
addresses, it has to start somewhere - and 0 is as good a place as
any. Thus, memory address 0 is a perfectly valid address (though
usually not within your program's realm).

So, combining the above two, if you want to consider the next
sizeof(type) bytes starting at memory address 0 as a data structure of
type type, you are perfectly welcome to do so. It is only when you try
to -access- those bytes (by dereferencing pointers) that the
OS-enforced memory protection kicks in and you start getting
segfaults. But you are allowed to do pointer arithmetic with those
addresses without the OS frowning at you (pointers - memory addresses
- are just unsigned longs in my linux x86 box, I can certainly take
the difference of two unsigned longs - who's stopping me as long as I
use the ISO C ptrdiff_t type to store the difference?).

Binand

Other related posts: