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;
}
相关推荐
RuoZoe3 天前
重塑WPF辉煌?基于DirectX 12的现代.NET UI框架Jalium
c语言
祈安_7 天前
C语言内存函数
c语言·后端
norlan_jame8 天前
C-PHY与D-PHY差异
c语言·开发语言
czy87874758 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
m0_531237178 天前
C语言-数组练习进阶
c语言·开发语言·算法
Z9fish9 天前
sse哈工大C语言编程练习23
c语言·数据结构·算法
代码无bug抓狂人9 天前
C语言之单词方阵——深搜(很好的深搜例题)
c语言·开发语言·算法·深度优先
CodeJourney_J9 天前
从“Hello World“ 开始 C++
c语言·c++·学习
枫叶丹49 天前
【Qt开发】Qt界面优化(七)-> Qt样式表(QSS) 样式属性
c语言·开发语言·c++·qt
with-the-flow9 天前
从数学底层的底层原理来讲 random 的函数是怎么实现的
c语言·python·算法