Re: what is the suggested way to do void * arithmetic ?

From: David Leimbach <leimy2k_at_mac.com>
Date: Thu, 10 Jul 2003 12:38:43 -0500
 I always feel better when I convert void * to char * but that's probably 
because C++ doesn't allow pointer arithmetic on void *'s.  The argument
being that you don't know the size of what's being pointed to with a void *
and therefore can't know how far to seek the the pointer to get to the next
valid address.

I think C takes a more low-level approach and says "void * is just an address
void * + 1 means the next valid address".

Anyway... it just seems to help when porting code between C/C++ to use
char *...

my $0.02.

Dave
On Thursday, July 10, 2003, at 11:40AM, Luigi Rizzo <rizzo_at_icir.org> wrote:

>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;
>            ^^^^^^^^^^^^^^
>
>sorry i meant   p = (void *)p + len;
>
>...
>> I don't understand the second one.  The first one blows up because
>> you aren't parenthesizing, e.g.:
>> 
>> 	next = (void *)(p + len);
>> 
>> The compiler is complaining because it doesn't know sizeof(*((void *)0))
>
>ok, it actually evaluates to 1 and i thought it was some standard, probably
>it is not so i guess i have to cast to (char *) instead
>
>	thanks
>	luigi
>
>> (pointer arithmatic is coerced to the type of the lvalue, in most
>> cases of casts).
>> 
>> Unless you are referencing them as array elements (in which case,
>> packing becomes a problem for you, when referencing them as arrays
>> of foo's, since you don't know how foo's are packed in an array),
>> you should probably cast them to char for the arithmatic, and add
>> them with byte counts.
>> 
>> -- Terry
>_______________________________________________
>freebsd-current_at_freebsd.org mailing list
>http://lists.freebsd.org/mailman/listinfo/freebsd-current
>To unsubscribe, send any mail to "freebsd-current-unsubscribe_at_freebsd.org"
>
>
Received on Thu Jul 10 2003 - 08:38:44 UTC

This archive was generated by hypermail 2.4.0 : Wed May 19 2021 - 11:37:14 UTC