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

本文详细介绍了C++中如何创建结构体指针和结构体对象,包括初始化、置空和赋值操作。同时,讨论了如何在结构体和std::string之间进行转换,为理解和使用C++结构体提供了实用指导。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值