memset
用来对一段内存空间全部设置为某个字符,一般用在对定义的字符串进行初始化为‘ '或‘/0';例:char a[100];memset(a, '/0', sizeof(a));
memcpy 用来做内存拷贝,你可以拿它拷贝任何数据类型的对象,可以指定拷贝的数据长度;例:char a[100],b[50]; memcpy(b, a, sizeof(b));注意如用sizeof(a),会造成b的内存地址溢出。
strcpy 就只能拷贝字符串了,它遇到'/0'就结束拷贝;例:char a[100],b[50];strcpy(a,b);如用strcpy(b,a),要注意a中的字符串长度(第一个‘/0'之前)是否超过50位,如超过,则会造成b的内存地址溢出。
strcpy
原型:extern char *strcpy(char *dest,char *src);
用法:#include
功能:把src所指由NULL结束的字符串复制到dest所指的数组中。
说明:src和dest所指内存区域不可以重叠且dest必须有足够的空间来容纳src的字符串。
返回指向dest的指针。
memcpy
原型:extern void *memcpy(void *dest, void *src, unsigned int count);
用法:#include
功能:由src所指内存区域复制count个字节到dest所指内存区域。
说明:src和dest所指内存区域不能重叠,函数返回指向dest的指针。
Memset
原型:extern void *memset(void *buffer, char c, int count);
用法:#include
功能:把buffer所指内存区域的前count个字节设置成字符c。
memcpy 用来做内存拷贝,你可以拿它拷贝任何数据类型的对象,可以指定拷贝的数据长度;例:char a[100],b[50]; memcpy(b, a, sizeof(b));注意如用sizeof(a),会造成b的内存地址溢出。
strcpy 就只能拷贝字符串了,它遇到'/0'就结束拷贝;例:char a[100],b[50];strcpy(a,b);如用strcpy(b,a),要注意a中的字符串长度(第一个‘/0'之前)是否超过50位,如超过,则会造成b的内存地址溢出。
strcpy
原型:extern char *strcpy(char *dest,char *src);
用法:#include
功能:把src所指由NULL结束的字符串复制到dest所指的数组中。
说明:src和dest所指内存区域不可以重叠且dest必须有足够的空间来容纳src的字符串。
返回指向dest的指针。
memcpy
原型:extern void *memcpy(void *dest, void *src, unsigned int count);
用法:#include
功能:由src所指内存区域复制count个字节到dest所指内存区域。
说明:src和dest所指内存区域不能重叠,函数返回指向dest的指针。
Memset
原型:extern void *memset(void *buffer, char c, int count);
用法:#include
功能:把buffer所指内存区域的前count个字节设置成字符c。
说明:返回指向buffer的指针。
程序例
example1
作用:将s中的字符串复制到字符数组d中。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
// memcpy.c
#include <stdio.h>
#include <string.h>
int
main()
{
char
*s=
"Golden Global View"
;
char
d[20];
clrscr();
memcpy
(d,s,(
strlen
(s)+1));
printf
(
"%s"
,d);
getchar
();
return
0;
}
|
输出结果:Golden Global View
example2
作用:将s中第14个字符开始的4个连续字符复制到d中。(从0开始)
1
2
3
4
5
6
7
8
9
10
11
12
|
#include <string.h>
int
main()
{
char
*s=
"Golden Global View"
;
char
d[20];
memcpy
(d,s+14,4);
//从第14个字符(V)开始复制,连续复制4个字符(View)
//memcpy(d,s+14*sizeof(char),4*sizeof(char));也可
d[4]=
'\0'
;
printf
(
"%s"
,d);
getchar
();
return
0;
}
|
输出结果: View
example3
作用:复制后覆盖原有部分数据
1
2
3
4
5
6
7
8
9
10
11
|
#include <stdio.h>
#include <string.h>
int
main(
void
)
{
char
src[] =
"******************************"
;
char
dest[] =
"abcdefghijlkmnopqrstuvwxyz0123as6"
;
printf
(
"destination before memcpy: %s\n"
, dest);
memcpy
(dest, src,
strlen
(src));
printf
(
"destination after memcpy: %s\n"
, dest);
return
0;
}
|
输出结果:
destination before memcpy:abcdefghijlkmnopqrstuvwxyz0123as6
destination after memcpy: ******************************as6