当前位置: C语言 -- 附录 -- memcpy_s

memcpy_s函数


概要:
#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>
errno_t memcpy_s(void * restrict s1, rsize_t s1max,
      const void * restrict s2, rsize_t n);

描述:

该函数从参数s2指向的对象复制n个字符到参数s1指向的对象。


运行约束:

参数s1和参数s2不能是空指针。参数s1max和参数n应不大于宏RSIZE_MAX。参数n应不大于参数s1max。复制不应发生在重叠对象之间。

在存在运行约束冲突的情况下,如果参数s1不是空指针并且参数s1max不大于宏RSIZE_MAX,函数向参数s1指向对象的前s1max个字符存储0


参数:
void * restrict s1

指向目标对象的指针,复制的内容将存入该对象。

rsize_t s1max

目标对象中修改的最大字符数。

const void * restrict s2

指向源对象的指针,将从该对象复制内容。

rsize_t n

复制的字符数。


返回值:

如果不存在运行约束冲突,函数返回0;否则函数返回非0值。


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
/*安全函数memcpy_s范例*/

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <string.h>

#define LENGTH 100

int main(void)
{
    const char source[] = "All for one, one for all.";
    char destination[LENGTH];
    
    if(!memcpy_s(destination, LENGTH, source, sizeof(source)/sizeof(char)))
        puts(destination);
    
    return 0;
}


输出:

All for one, one for all.

注:使用Visual Studio编译。


相关内容:
memcpy 复制内存区域字符序列的函数。
memmove_s 移动内存区域字符序列的安全函数。
strcpy_s 复制字符串的安全函数。
strncpy_s 从字符串中复制限定数量字符的安全函数。