Strange Output

K

KellyB

#include <stdio.h>
#include <limits.h>

void printbin(void* num) {
size_t i, j;
unsigned char *pc = (unsigned char* )&num;
pc += sizeof(num) - 1;

for (i = 0 ; i < sizeof(num) ; pc--, i++ ) {
for ( j = 0; j < CHAR_BIT ; j++ ) {
putchar( *pc & ( 1 << (CHAR_BIT - j - 1) ) ? '1' : '0');
}
putchar(' ');
}
return ;
}

int main(void) {

size_t i, j;
float obj = 1234.0;
float obj1 = 1234.0;
unsigned char *pc = (unsigned char* )&obj;
pc += sizeof(obj) - 1;

for (i = 0 ; i < sizeof(obj) ; pc--, i++ ) {
for( j = 0; j < CHAR_BIT ; j++ ) {
putchar( *pc & ( 1 << (CHAR_BIT - j - 1) ) ? '1' : '0');
}
putchar(' ');
}
puts("");

printbin(&obj1);
return 0;
}

This is the output :
01000100 10011010 01000000 00000000
00000000 00011101 11111110 11100100

Why is it so ? It seems very strange.Can anyone please help me
understand whats going on here?

PS: I am using a little-endian processor
 
K

KellyB

pete said:
That has a major problem,
which is related to the reply that you got from Martin Ambuhl.

As it stands, there is no way to determine
the size of the object that (num) points to.

sizeof(num) equals sizeof(void *).


You need:

#include <stddef.h>
void printbin(void* num, size_t size);

Aah ..Thanks Martin and Pete . Got it.
 
B

Ben Bacarisse

KellyB said:
#include <stdio.h>
#include <limits.h>

void printbin(void* num) {
size_t i, j;
unsigned char *pc = (unsigned char* )&num;

The & is wrong. You already have the address.
pc += sizeof(num) - 1;

And the size will be wrong. The size of the print is not the size of
the object.
for (i = 0 ; i < sizeof(num) ; pc--, i++ ) {
for ( j = 0; j < CHAR_BIT ; j++ ) {
putchar( *pc & ( 1 << (CHAR_BIT - j - 1) ) ? '1' : '0');
}
putchar(' ');
}
return ;
}

int main(void) {

size_t i, j;
float obj = 1234.0;
float obj1 = 1234.0;
unsigned char *pc = (unsigned char* )&obj;
pc += sizeof(obj) - 1;

Both OK here, though.
for (i = 0 ; i < sizeof(obj) ; pc--, i++ ) {

There is a subtlety about running pointer loops backwards in that you
can't even construct a pointer that points "before" the first byte of
the object (you don't access it, but even constructing it is
technically undefined behaviour). You won't, in practise, experience
a problem though.
 

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

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,563
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top