C语言内存函数

各位少年,大家好我是博主那一脸阳光,今天分享内存函数的使用和模拟实现。

memcpy 使⽤和模拟实现

c 复制代码
void * memcpy ( void * destination, const void * source, size_t num );

• 函数memcpy从source的位置开始向后复制num个字节的数据到destination指向的内存位置。

• 这个函数在遇到 '\0' 的时候并不会停下来。

• 如果source和destination有任何的重叠,复制的结果都是未定义的。

c 复制代码
#include <stdio.h>
#include <string.h>
int main()
{
 int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
 int arr2[10] = { 0 };
 memcpy(arr2, arr1, 20);
 int i = 0;
 for (i = 0; i < 10; i++)
 {
 printf("%d ", arr2[i]);
 }
 return 0;
}

对于重叠的内存,交给memmove来处理。

memcpy函数的模拟实现:

c 复制代码
void * memcpy ( void * dst, const void * src, size_t count)
{
 void * ret = dst;
 assert(dst);
 assert(src);
 /*
 * copy from lower addresses to higher addresses
 */
 while (count--) {
 *(char *)dst = *(char *)src;
 dst = (char *)dst + 1;
 src = (char *)src + 1;
 }
 return(ret);
}

memmove 使⽤和模拟实现

c 复制代码
void * memmove ( void * destination, const void * source, size_t num );

和memcpy的差别就是memmove函数处理的源内存块和⽬标内存块是可以重叠的。

如果源空间和⽬标空间出现重叠,就得使⽤memmove函数处理。

#include <stdio.h>

c 复制代码
#include <string.h>
int main()
{
 int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
 memmove(arr1+2, arr1, 20);
 int i = 0;
 for (i = 0; i < 10; i++)
 {
 printf("%d ", arr2[i]);
 }
  return 0;
}

输出的结果:

c 复制代码
1 2 1 2 3 4 5 8 9 10

memset 函数的使⽤

c 复制代码
void * memset ( void * ptr, int value, size_t num );

memset是⽤来设置内存的,将内存中的值以字节为单位设置成想要的内容。

c 复制代码
#include <stdio.h>
#include <string.h>
int main ()
{
 char str[] = "hello world";
 memset (str,'x',6);
 printf(str);
 return 0;
}
c 复制代码
xxxxxxworld

memcmp 函数的使⽤

c 复制代码
int memcmp ( const void * ptr1, const void * ptr2, size_t num );

• ⽐较从ptr1和ptr2指针指向的位置开始,向后的num个字节

• 返回值如下:

c 复制代码
#include <stdio.h>
#include <string.h>
int main()
{
 char buffer1[] = "DWgaOtP12df0";
 char buffer2[] = "DWGAOTP12DF0";
 int n;
 n = memcmp(buffer1, buffer2, sizeof(buffer1));
 if (n > 0) 
 printf("'%s' is greater than '%s'.\n", buffer1, buffer2);
 else if (n < 0) 
 printf("'%s' is less than '%s'.\n", buffer1, buffer2);
 else
 printf("'%s' is the same as '%s'.\n", buffer1, buffer2);
 return 0;
}
相关推荐
fie88895 分钟前
基于MATLAB的狼群算法实现
开发语言·算法·matlab
gihigo19987 分钟前
MATLAB中生成混淆矩阵
开发语言·matlab·矩阵
曾几何时`23 分钟前
C++——this指针
开发语言·c++
小冯的编程学习之路37 分钟前
【C++】: C++基于微服务的即时通讯系统(1)
开发语言·c++·微服务
穿西装的水獭2 小时前
python将Excel数据写进图片中
开发语言·python·excel
老友@2 小时前
Java Excel 导出:EasyExcel 使用详解
java·开发语言·excel·easyexcel·excel导出
tryCbest2 小时前
Python基础之爬虫技术(一)
开发语言·爬虫·python
hixiong1232 小时前
C# OpenCVSharp实现Hand Pose Estimation Mediapipe
开发语言·opencv·ai·c#·手势识别
集成显卡2 小时前
AI取名大师 | PM2 部署 Bun.js 应用及配置 Let‘s Encrypt 免费 HTTPS 证书
开发语言·javascript·人工智能
AI小云2 小时前
【Numpy数据运算】数组间运算
开发语言·python·numpy