[C Language] The key points that need attention when using snprintf to transmit cache information. The key points of snprintf
I. snprintf function description
The snprintf function is defined as: int snprintf (char * str, size_t size, const char * format ,...);
The function is a formatted Conversion Function and uses '\ 0' as the Terminator.
However, if you don't pay attention to it, it will produce inexplicable results, and when there are many codes, locating is also troublesome,
Therefore, it is necessary to explain here.
Ii. incorrect use of snprintf
Not to mention, paste the Code directly and output the result.
<Span style = "font-size: 12px;" >#include <stdio. h> # include <string. h> typedef struct _ T_TEST {int a; int B;} T_TEST, * PT_TEST; int main (void) {T_TEST tTest; memset (& tTest, 0, sizeof (tTest); tTest. a = 1; tTest. B = 2; printf ("tTest. a = % d, tTest. B = % d. \ n ", tTest. a, tTest. b); char buf [128] = {0}; snprintf (buf, sizeof (buf), "% s", (char *) & tTest ); // copy the struct to the buf PT_TEST ptTest = (PT_TEST) buf; printf ("ptTest-> a = % d, ptTest-> B = % d. \ n ", ptTest-> a, ptTest-> B); return 0;} running result: [root @ f8s function_test] #. /snprintf_test tTest. a = 1, tTest. B = 2. ptTest-> a = 1, ptTest-> B = 0. // here, the integer B is changed to 0 [root @ f8s function_test] # </span>
The cause is: Because snprintf uses '\ 0' as the Terminator, when the character is copied, The T_TEST struct has an Terminator, so it is truncated.
Iii. Solution
Use the memcpy function instead of snprintf.
<Span style = "font-size: 12px;" >#include <stdio. h> # include <string. h> typedef struct _ T_TEST {int a; int B;} T_TEST, * PT_TEST; int main (void) {T_TEST tTest; memset (& tTest, 0, sizeof (tTest); tTest. a = 1; tTest. B = 2; printf ("tTest. a = % d, tTest. B = % d. \ n ", tTest. a, tTest. b); char buf [128] = {0}; // snprintf (buf, sizeof (buf), "% s", (char *) & tTest ); memcpy (buf, (char *) & tTest, sizeof (buf); PT_TEST ptTest = (PT_TEST) buf; printf ("ptTest-> a = % d, ptTest-> B = % d. \ n ", ptTest-> a, ptTest-> B); return 0;} running result: [root @ f8s function_test] #. /memcpy_testtTest.a = 1, tTest. B = 2. ptTest-> a = 1, ptTest-> B = 2. [root @ f8s function_test] # </span>