Convert struct to character array

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.