Void Pointer Question

H

herrcho

#include <stdio.h>

int multi[2][4];

int main()
{
printf("\nmulti = %p",(void *)multi);
printf("\nmulti[0] = %p",(void *)&multi[0]);
printf("\nmulti[0] = %p",(void *)multi[0]);
printf("\n&multi[0][0] = %p\n",(void *)&multi[0][0]);
return 0;
}

as far as i know.. the above code is alright..

what i'd like to ask is why should (void *) put there .

what's the difference if i change 'pointer to array or pointer to
integer' to 'pointer to void' like above ?

TIA
 
T

Tom Zych

herrcho said:
printf("\nmulti = %p",(void *)multi); [snip]

what i'd like to ask is why should (void *) put there .
what's the difference if i change 'pointer to array or pointer to
integer' to 'pointer to void' like above ?

Usually, if a function expects void * and you pass it something_else
*, the compiler will just cast to void *. It can't do that for
printf() and other variadic functions, because the prototype says
"..." and it doesn't know what the types should be. So, when using
%p and something_else *, always cast to void *.
 
B

Barry Schwarz

#include <stdio.h>

int multi[2][4];

int main()
{
printf("\nmulti = %p",(void *)multi);
printf("\nmulti[0] = %p",(void *)&multi[0]);
printf("\nmulti[0] = %p",(void *)multi[0]);
printf("\n&multi[0][0] = %p\n",(void *)&multi[0][0]);
return 0;
}

as far as i know.. the above code is alright..

what i'd like to ask is why should (void *) put there .

what's the difference if i change 'pointer to array or pointer to
integer' to 'pointer to void' like above ?
For variadic functions, variable arguments cannot be coerced to the
"correct" type since that type is unknown. (There is an exception for
some integer and double promotions which don't apply here.)

%p tells printf that the corresponding argument will have type pointer
to void so it is you job to make sure that it does.

On the systems I'm familiar with, all pointers have the same size and
representation so the cast is essentially a nop. BUT, there is no
requirement for this consistency. It is legal/possible for a void* to
be eight bytes while a pointer to array is four bytes or for one to be
big endian and the other little endian. On such systems, omitting the
cast would cause undefined behavior.


<<Remove the del for email>>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,082
Messages
2,570,588
Members
47,210
Latest member
JuliaMulli

Latest Threads

Top