1. 程式人生 > >關於結構體與字符串相互轉換驗證

關於結構體與字符串相互轉換驗證

client file define 知識 字節 bsp std print argc

/*************************************************************************
    > File Name: memtest.c
    > Author: 
    > Mail: 
    > Created Time: Thu 27 Dec 2018 05:47:37 PM CST
 ************************************************************************/

#include<stdio.h>
#define N 50
#define
IPSIZE 15 struct ClientInfo{ char headName[N]; char name[N]; int num; char ip[IPSIZE]; }; int main(int argc,char **argv) { struct ClientInfo aaa; strcpy(aaa.headName,"aaaaaaaaaaaaa"); strcpy(aaa.name,"bbbbbbbbb"); aaa.num = 10; strcpy(aaa.ip,
"ccccccc"); char buf[200]; memcpy(buf,&aaa,sizeof(aaa)); struct ClientInfo bbb; memcpy(&bbb,buf,sizeof(bbb)); printf("%s\n",bbb.headName); printf("%s\n",bbb.name); printf("%d\n",bbb.num); printf("%s\n",bbb.ip); }

輸出結果:

aaaaaaaaaaaaa
bbbbbbbbb
10
ccccccc

這裏要註意結構體的字節對齊規則

後續會把相關知識錄入博客

關於結構體與字符串相互轉換驗證