planetzoom said:
I'd either convert the void* value to char* using a cast, or assign it
to a char* object if that happens to be more convenient.
Ok, thank you Keith. 'gcc -Wall' does give a warning without the cast, but
that's probably because it has no way of knowing to what the void * points.
printf("%p\n", &array[0]);
Assuming this line were added to the above code, a cast here would also be
recommended for the same reason, even though void* and char* are guaranteed
to have the same representation?
printf("%p\n", (void *) &array[0]);
An argument could be made either way. The language pretty much
guarantees that passing a char* value for a "%p" format specifier will
work correctly.
But that guarantee exists only for historical reasons, and IMHO
depending on it is questionable style. The guarantee applies only to
pointers to char (and signed char, and unsigned char), not to pointers
to other types. The type of the array is not obvious from the printf
statement, so to verify that it's correct you'd have to hunt down the
declaration and remember the arbitrary equivalence rule. Without the
cast, the code can break if you change the type of array. If I see a
statement like that without the cast, it's hard to tell whether it was
written by a clever programmer who knows about the standard's
guarantee that char* and void* are equivalent, or by a less clever
programmer who thinks all pointers look alike.
So yes, it will work without the cast, but I'd recommend using a cast
anyway. (This is a rare case where a cast is a good idea; in most
contexts, casts should be avoided.)
You could also avoid the cast by assigning the address to a variable:
void *addr = &array[0]; /* implicit conversion from char* to void* */
printf("%p\n", addr);
But I wouldn't bother creating a variable like that just to avoid the
cast.