When I solved the problem of sending a struct through socket last night, I realized that the struct can be converted into a string before being sent, but before today, I have been wondering whether to solve the problem (to facilitate the description, remove the socket part). First, let's look at the Code:
#include <stdlib.h>#include <stdio.h>#include <string.h>typedef struct info{char name[5];char num[10];}INFO;int main(){INFO info;char buf[15];strcpy(info.name, "won");strcpy(info.num, "12345");memcpy(buf, &info, sizeof(info));printf("%s\n", buf);printf("%d\n", (int)strlen(buf));exit(0);}
After compilation and running, it is found that only the value of the first variable is printed "won", but "12345" is not printed. In addition, the Buf length is 3 rather than 8. Why? Didn't the struct be fully converted into a string?
This morning, I suddenly remembered that both the printf () function and strlen () function returned when an ending character exists !!! In fact, the content in the Buf array is "won \ 012345 \ 0 ". Therefore, only "won" can be printed ".
To confirm this idea, you can replace the print statement:
int i = 0;while(i < 15){printf("%c", buf[i]);i++;}printf("\n");
Print "won12345" After compiling and running ".
Another better way is to convert a string into a corresponding struct (this is the final purpose). The following code is used:
#include <stdlib.h>#include <stdio.h>#include <string.h>typedef struct info{char name[5];char num[10];}INFO;int main(){INFO info, info1;char buf[15];strcpy(info.name, "won");strcpy(info.num, "12345");memcpy(buf, &info, sizeof(info));memcpy(&info1, buf, sizeof(buf));printf("%s,%s\n", info1.name, info1.num);exit(0);}
Use memcpy (& info1, Buf, sizeof (Info); to convert the content of the character array Buf to the struct info1. After compilation, the result is: "Won, 12345 ".
Successful!
Convert struct to character array