问题
I have two objects, Header, and DF. lets say
header = CCCCCC7E
and
DF = 01020304,
shouldnt the value of the buffer be CCCCCC7E01020304?
for some reason when i printed it i got:
7EFFFFFFCCFFFFFFCCFFFFFFCCFFFFFFCCFFFFFFCCFFFFFFCCFFFFFFCCFFFFFFCCFFFFFFCC00FFFF
FFCC00000000000004030201FFFFFF8967341200000000
this is how i printed it:
for (int i = 0; i < sizeof(buffer); i++)
{ printf("%02X", buffer[i]); }
this is the code:
struct Header header;
struct Data_Format DF;
unsigned char buffer[TOTAL_SIZE];
header.Start = 0x7E;
header.Options = 0x00;
header.PacketLength = 0x00;
header.VCP = 0x00;
header.Reserved = 0x00;
header.Return = 0x00;
DF.Address = 0x01020304; //real value: NULL
DF.Result = 0x1234; //real value: NULL
DF.Size = 0x6789; //real value: NULL
memcpy(buffer,&header, sizeof(Header));
memcpy(buffer+sizeof(Header), &DF, sizeof(Data_Format));
回答1:
From the partial code given it doesn't give much idea but Some point need to do.
Do a memset always before coping to the buffer.
memset(buffer, 0, sizeof(buffer))
This will prevent you to get the junk.
回答2:
The objects are not neccessarily packed together. Acctually, most compilers allign objects at 8 bytes border so that the data will be accessed at higher speed. The bytes between the objects will just be leaved uninitialized (sometimes the debug-version of runtime environment will fill the gap with invalid data).
回答3:
This is not a proper way [because of compiler optimizations and alignment] to achieve what you want.
However, just for a logical suggestion, in your code, change
for (int i = 0; i < sizeof(buffer); i++)
to
for (int i = 0; i < (sizeof(Header) + sizeof(Data_Format)); i++).
This will limit the loop till valid entries. Remember, even after this change you're not guaranteed [actually,not supposed to] get the proper result.
EDIT
you can achieve your target using snprintf(). A common usage looks like
snprintf(buf, sizeof(buf), "%x%x%x", header.start, header.options, DF.size); //incomplete list
printf("%s", buf);
来源:https://stackoverflow.com/questions/25760847/c-why-is-my-buffer-not-printing-properly