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

来源:互联网 发布:java监听端口接收数据 编辑:程序博客网 时间:2024/05/17 09:27
#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 也有三个参数,一个目标地址,源地址,和 大小。