Stochelo
Stochelo

Reputation: 153

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!

Upvotes: 0

Views: 637

Answers (2)

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

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

I don't know why I have the value "31" written and not the value "01" as wanted.

The reason you see 31 is that your chain of functions interprets the value 1 twice:

  • First, sprintf interprets it as a character representing a hex digit
  • Second, PRINT_OPAQUE_STRUCT interprets the value again, now as a hex number

Essentially, sprintf converts 1 to its character representation, which is '1'. On your system, its code is 0x31, hence the output that you get.

You need to remove one of these two interpretations to get your code to print 1. To remove the first interpretation, simply assign 1 to the pointer, like this:

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

To remove the second interpretation, print with %c instead of %x in PRINT_OPAQUE_STRUCT (which may not be possible).

Upvotes: 1

Related Questions