您的位置:首页 > 其它

结构体指针和结构体对象的创建、置空、赋值以及与string的转换

2013-07-02 21:16 417 查看
typedef struct Info
{
char name[5];
char addr[10];
int age;
double salary;
}tInfo, *pInfo;
//tInfo为结构体Info的别名

struct stTest
{
char name[5];
char addr[10];
int age;
double salary;
};

int _tmain(int argc, _TCHAR* argv[])
{
//结构体指针的创建、置空、赋值
pInfo info = new tInfo();
memset(info, 0 ,sizeof(tInfo));
info->age = 10;
strcpy(info->name, "zhou");
strcpy(info->addr,"shandong");
info->salary = 123.123;

//指针的大小为4,结构体的大小采用对齐模式,32位下是4字节对齐
//下面的计算为:32 = 8+12+4+8
int a = sizeof(tInfo);//32
int b = sizeof(Info);//32
int c = sizeof(pInfo);//4
int d = sizeof(info);//4

//结构体转为string
string str;
str.assign((const char*)info, sizeof(tInfo));
//把string转为结构体
pInfo get = new tInfo();
memcpy(get, str.c_str(), str.size());

//结构体对象创建、置空、赋值
stTest st;
memset(&st, 0, sizeof(stTest));
strcpy(st.addr, "shandong");
strcpy(st.name, "zhou");
st.age = 33;
st.salary = 6000.37;

//结构体转为string
string temp;
temp.assign((const char*)&st, sizeof(st));
//string转为结构体
stTest stget;
memcpy(&stget, temp.c_str(), temp.size());

//结构体指针的创建
stTest* aa = &stget;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐