Stochelo Stochelo - 1 year ago 83
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;

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

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 :


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?


Answer Source

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'.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download