what is the suggested way to do void * arithmetic ?

Harti Brandt brandt at fokus.fraunhofer.de
Thu Jul 10 02:24:11 PDT 2003


On Thu, 10 Jul 2003, Luigi Rizzo wrote:

LR>
LR>Hi,
LR>in several places in ipfw2.c i have to move pointers across
LR>structures of variable length (lists of ipfw2 instructions
LR>returned by the getsockopt()), and i use the following type of code:
LR>
LR>	void *next;
LR>	foo *p;
LR>
LR>	...
LR>
LR>	next = (void *)p + len;
LR>	...
LR>	foo = (foo *)p + len;
LR>
LR>When using WARNS=5, the compiler in -current flags them with 'Warning
LR>void * arithmetic'.
LR>
LR>What is the best way to do the above given that i do need to use
LR>these variable-size structures ?

Because sizeof(char), sizeof(unsigned char) and sizeof(signed char) all
are defined to be 1 by the standard, any of them'll do it. Arithmetic on
void pointers is undefined by the standard.

next_foo = (struct foo *)((char *)this_foo + this_foo->len);

provided that the object pointed to by this_foo is at least this_foo->len
bytes long.

harti
-- 
harti brandt,
http://www.fokus.fraunhofer.de/research/cc/cats/employees/hartmut.brandt/private
brandt at fokus.fraunhofer.de, harti at freebsd.org


More information about the freebsd-current mailing list