Stochelo Stochelo - 3 days ago 7
C Question

Writing one byte in struct variable

I'm trying to modify one byte of my structure with the following code :

struct example *dev;

PRINT_OPAQUE_STRUCT(dev);
sprintf((char*) dev + 24, "%x",1);
PRINT_OPAQUE_STRUCT(dev);


The PRINT_OPAQUE_STRUCT is just printing the content of the structure, and is defined in this other topic :
Print a struct in C

The output of this program is :


d046f64f20b3fb4f00000000e047f64f00000000ffffffff000000
d046f64f20b3fb4f00000000e047f64f00000000ffffffff310000


I don't know why I have the value "31" written and not the value "01" as wanted. I tried to replace the second argument of sprintf with "%01x" but it didn't change anything. Anyone knows why?

Thanks!

Answer

Well, you are formatting the value 1 as a string. That's what sprintf does. 0x31 is the character code for the character '1'. If you just want to write the byte value 0x01 into your struct, then you don't need sprintf. Just do this:

*((char*)dev + 24) = 1;

or (the same, but with slightly different syntax):

((char*)dev)[24] = 1;

Note also, like one comment below says, sprintf will not just write one single byte. Since it writes a string, and C strings are null-terminated, it will also write a null character ('\0', 0x00) right after the '1'.

Comments