016-C语言内存函数

C语言内存函数

文章目录

  • C语言内存函数
    • [1. memcpy](#1. memcpy)
    • [2. memmove](#2. memmove)
    • [3. memset](#3. memset)
    • [4. memcmp](#4. memcmp)

注意: 使用这些函数需要包含 string.h头文件。

1. memcpy

c 复制代码
void * memcpy ( void * destination, const void * source, size_t num );
  • source指向的位置开始,向后复制num个字节的内容到destination中。
  • 复制过程中,不在乎内容是什么,无论是什么内容都是照搬。
  • destinationsource指向的空间中有任何的重叠部分,那么它们复制的结果都是未定义的。
  • 需要注意的是,在拷贝字符串时,如果拷贝的内容最后一个位置不是\0,最好在拷贝结束后加上\0,否则后期可能造成越界访问。
c 复制代码
#include <stdio.h>
#include <string.h>

int main()
{
	char* s1 = "hello memcpy";
	char s2[50];
	memcpy(s2, s1, ((strlen(s1) + 1) * sizeof(s1[0])));
	printf("%s\n", s2);

	return 0;
}

2. memmove

c 复制代码
void * memmove ( void * destination, const void * source, size_t num );
  • memcpy不同的是memmovedestinationsource指向的部分是可以重叠的。
c 复制代码
#include <stdio.h>
#include <string.h>

int main()
{
	char s1[100] = "hello memmove 123456789";
	memcpy(s1 + 14, s1, 13 * sizeof(s1[0]));
	printf("%s\n", s1);

	return 0;
}

3. memset

c 复制代码
void * memset ( void * ptr, int value, size_t num );
  • ptr指向的内存的num个字节的内存全部设置成value
c 复制代码
#include <stdio.h>
#include <string.h>

int main()
{
	char s1[100] = "hello memset";
	memset(s1, 'C', 3);
	printf("%s\n", s1);

	return 0;
}

4. memcmp

c 复制代码
int memcmp ( const void * ptr1, const void * ptr2, size_t num );
  • 比较ptr1ptr2指向的位置开始,向后的num个字节的内容。
  • 如果ptr1指向的内容小于ptr2指向的内容,则返回值<0
  • 如果ptr1指向的内容等于ptr2指向的内容,则返回值==0
  • 如果ptr1指向的内容大于ptr2指向的内容,则返回值>0
c 复制代码
#include <stdio.h>
#include <string.h>

int main()
{
	char s1[] = "123456789";
	char s2[] = "234567890";
	printf("%d\n", memcmp(s1, s2, 5 * sizeof(char)));

	return 0;
}
相关推荐
啧不应该啊12 小时前
Day1 python与c宏观区别
c语言·开发语言
OneT1me12 小时前
CVE-2026-31431 的C语言版本
c语言·开发语言·安全威胁分析
爱编码的小八嘎14 小时前
C‘语言完美演绎9-11
c语言
一行代码一行诗++14 小时前
C语言中if的使用
c语言·c++·算法
来生硬件工程师14 小时前
【程序库】 MutiButton 按键库
c语言·笔记·stm32·单片机·mcu·嵌入式实时数据库
wljy114 小时前
牛客每日一题(2026.4.30) 整数域二分
c语言·c++·算法·蓝桥杯·二分
多看多敲多思考14 小时前
华润微CS32ME10 MCU使用教程(1)---CS32ME10之GPIO使用
c语言·stm32·单片机·嵌入式硬件·mcu
Navigator_Z15 小时前
LeetCode //C - 1030. Matrix Cells in Distance Order
c语言·算法·leetcode
无敌昊哥战神15 小时前
【回溯算法巅峰之作】LeetCode 51. N皇后问题详解与常见避坑指南 (C/C++/Python)
c语言·算法·leetcode