Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

printf - C - Why is my buffer not printing properly?

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));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...