C++ 中使用memset和memcpy 对字符串和字符串数组处理

本文展示了一个使用C++进行内存复制和初始化的例子,通过具体的代码实现解释了如何利用memcpy和memset函数处理结构体数据。

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

#include <iostream>
#include <string.h>
using namespace std;
struct SomeInfo
{
	char id[30];
	char name[30];
};

struct TotalInfo
{
	char total[20];
	SomeInfo my[10];
};

class myClass
{
	public:
	myClass()
	{
	}

	~myClass()
	{
	}

    void memcopy(int ,TotalInfo);
	void print();
	private:
	TotalInfo m_totalInfo;
	int m_count;
};


void myClass::memcopy(int count ,TotalInfo info)
{
	m_count = count;
	memcpy(&m_totalInfo,&info,sizeof(m_totalInfo));
}
void myClass::print()
{
	std::cout << m_totalInfo.total << std::endl;
	for (int i = 0; i != m_count ; ++i)
	{
	  std::cout << m_totalInfo.my[i].id << std::endl;
	  std::cout << m_totalInfo.my[i].name << std::endl;
	}
}
int main()
{
	myClass here = myClass();
	TotalInfo totalInfo;
	memset(&totalInfo, 0, sizeof(totalInfo));
	char total[20] = "totalInfo.total"; 
	memcpy(totalInfo.total,total,20); 
	int count = 5;
	for (int i = 0; i != count ; ++i)
	{
		char _id[30] = "totalInfo.Some.id";
		char _name[30] = "totalInfo.Some.name";
		memcpy(totalInfo.my[i].id, _id,sizeof(_id));
		memcpy(totalInfo.my[i].name, _name,sizeof(_name));
	}
	here.memcopy(count, totalInfo);
	here.print();
	return 0;
}


在main函数的第三行,memset初始化新申请的内存。memset:作用是在一段内存块中填充某个给定的值,它是对较大的结构体数组进行清零操作的一种最快方法[1]

一共三个参数,地址,请零(目前做的是清零动作,而不是char型值),地址空间大小。


memcpy 也有三个参数,一个目标地址,源地址,和 大小。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值