[Gllug] Pointer arithmetic with void *
Alain Williams
addw at phcomp.co.uk
Wed Aug 14 15:24:21 UTC 2002
On Wed, Aug 14, 2002 at 04:15:06PM +0100, Tethys wrote:
>
> Just curious. Does anyone know what the C standard says about pointer
> arithmetic with void *? for example:
>
> void *ptr;
>
> ptr = mmap(NULL, 1024, PROT_READ, MAP_SHARED, fd, 0);
> ptr++;
>
> Where is ptr pointing? 1 byte from the start of the file? One
> "pointer length" (i.e., 4 or 8 bytes from the start of the file)?
> Something else entirely?
>
> Empirical evidence shows it to be a 1 byte increment on Linux and
> Solaris, but can this be relied upon, or is it just an implementation
> detail of gcc (which I used on both)? K&R doesn't say either way, and
> I don't want to be making assumptions that may prove non-portable.
You can't do it, it is illegal. The point is that on a byte addressed m/c
(like most that you are used to)
ptr++
compiles to:
ptr += sizeof(*ptr)
Since void* doesn't point to anything in particular it doesn't know what *ptr
is and so doesn't know how big it is. [[It get more interesting with m/cs with
other addressing schemes]].
If gcc is allowing this, it is breaking the standard. Try compiling with the
-pedantic flag. If you want to do this sort of thing, you should
cast via char*:
ptr = (void*)((char*)ptr + 1);
Not so neat, but ...
--
Alain Williams
#include <std_disclaimer.h>
--
Gllug mailing list - Gllug at linux.co.uk
http://list.ftech.net/mailman/listinfo/gllug
More information about the GLLUG
mailing list