void *

G

gyan

what is wrong in following code
int a=4;
void *p;
p = &a;
printf("%s",(char *)p);
above program doesn't print any output?
 
G

Gernot Frisch

gyan said:
what is wrong in following code
int a=4;
void *p;
p = &a;
printf("%s",(char *)p);
above program doesn't print any output?

Yes, a = hex "04 00 00 00" (big endian)
If you print if, the first 'char' has the value 4 - which cannot be
seen, the next has 0, which means end of string.
If you do:
int a=-1; printf("%s", &a); you will get a terrible error, since
you're accessing all memory after 'a' until one byte is zero.
 
N

nonamehkg

if you just want to print the address of p, do this:


int a=4;
void *p;
p = (void*)&a;
printf("%X",p);


or the value 4 in hex (in 32bit system):
int a=4;
void *p;
p = (void*)&a;
printf("%X",*((long*)p));
 
G

Gernot Frisch

nonamehkg said:
if you just want to print the address of p, do this:


int a=4;
void *p;
p = (void*)&a;
printf("%X",p);


or the value 4 in hex (in 32bit system):
int a=4;
void *p;
p = (void*)&a;
printf("%X",*((long*)p));

Address of is done by:
printf("%p", &somthething);
-Gernot
 
R

Ron Natalie

nonamehkg said:
if you just want to print the address of p, do this:


int a=4;
void *p;
p = (void*)&a;
printf("%X",p);
bzzt, UNDEFINED BEHAVIOR. %X expects a unsigned int argument
you gave it a pointer.

You must always give printf the right type argument. stdarg is
rather stupid that way.

"%p" by the way will print a pointer value when given a void*.
or the value 4 in hex (in 32bit system):
int a=4;
void *p;
p = (void*)&a;
printf("%X",*((long*)p));

Assuming int and long are the same effective type.
 
J

Jay Nabonne

Yes, a = hex "04 00 00 00" (big endian)

Actually, that's little endian. :)

And big endian would terminate even sooner (since the first byte would be
a zero).

- Jay
 
O

Old Wolf

Gernot said:
Address of is done by:
printf("%p", &somthething);

printf("%p", (void *)&something);

It's quite possible for (int *) to have different representation
to, or even to be be smaller than, (void *)
(eg. if int has alignment 4, then you do not need to bother to
store the bottom 2 bits which must always be 0).

That's bizarre, I wonder how he thinks that was better than:
printf("%X", a);

(or, to be pedantic, (unsigned)a )
 

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,197
Messages
2,571,041
Members
47,643
Latest member
ashutoshjha_1101

Latest Threads

Top