what is the suggested way to do void * arithmetic ?

Jens Schweikhardt schweikh at schweikhardt.net
Fri Jul 11 12:08:51 PDT 2003


On Thu, Jul 10, 2003 at 03:42:04AM -0700, Terry Lambert wrote:
# Luigi Rizzo wrote:
# > in several places in ipfw2.c i have to move pointers across
# > structures of variable length (lists of ipfw2 instructions
# > returned by the getsockopt()), and i use the following type of code:
# > 
# >         void *next;
# >         foo *p;
# >         next = (void *)p + len;
# >         foo = (foo *)p + len;
# > 
# > When using WARNS=5, the compiler in -current flags them with 'Warning
# > void * arithmetic'.
# > 
# > What is the best way to do the above given that i do need to use
# > these variable-size structures ?
# 
# I don't understand the second one.  The first one blows up because
# you aren't parenthesizing, e.g.:
# 
# 	next = (void *)(p + len);

Huh? next has type pointer-to-void so a cast is never necessary
to assign to it. This is the raison d'être for void pointers in C.

In standardese void is an incomplete type that can not be completed.
Incomplete types have no size. Therefore, any arithmetic on
pointer-to-void is undefined. One needs to cast to a non-void pointer
before doing arithmetic. Whether this is a char* or other depends on
what you want to do.

Some compilers by default assume sizeof(void) = 1 (e.g. the same as
char in all its qualifications) for simplicity, but this is far from
portable.

Regards,

	Jens
-- 
Jens Schweikhardt http://www.schweikhardt.net/
SIGSIG -- signature too long (core dumped)


More information about the freebsd-current mailing list