<cstring>和<cstdlib>中定义了内存操作函数,以下是常用的内存操作函数。
void* memchr(void* __p, int __c, size_t __n);在内存中查找指定字符串
int memcmp(const void*, const void*, size_t);比较两块内存中的字符
void* memcpy(void*, const void*, size_t);拷贝源内存块至目的内存块
void* memmove(void*, const void*, size_t);移动源内存块至目的内存块
void* memset(void*, int, size_t);使用指定数值设置内存块的内容
void* malloc(size);分配一块内存
void* calloc(size,n);分配size*n字节的内存,并清零
void free(void*);释放分配的内存
下面写个内存操作函数运用代码实例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
//梁笔记 //zouzhongliang.com #include <iostream> #include <cstring> #include <cstdlib> using namespace std; struct Point{ double x; double y; }; ostream& operator<<(ostream& cout, Point& point){ cout<<point.x<<","<<point.y; return cout; } int main() { Point p1 = {10,20}; Point p2 = {0,0}; Point p3 = {30,40}; cout<<p1<<endl; cout<<p2<<endl; cout<<"p1内存拷贝到p2"<<endl; memcpy((void*)&p2,(void*)&p1,sizeof(Point)); cout<<p1<<endl; cout<<p2<<endl; cout<<"p3内存移动到p1"<<endl; memcpy((void*)&p1,(void*)&p3,sizeof(Point)); cout<<p1<<endl; cout<<p3<<endl; cout<<"p1内存指定数值"<<endl; memset((void*)&p1,0,sizeof(Point)); cout<<p1<<endl; return 0; } |
内存操作函数调用测试结果:
1 2 3 4 5 6 7 8 9 10 |
10,20 0,0 p1内存拷贝到p2 10,20 10,20 p3内存移动到p1 30,40 30,40 p1内存指定数值 0,0 |