当前位置: C语言 -- 标准库 -- <string.h> -- memcpy

memcpy函数


概要:
#include <string.h>
void *memcpy(void * restrict s1, 
      const void * restrict s2, 
      size_t n);

描述:

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

如果复制发生在重叠对象之间,函数行为是未定义的。

ISO/IEC 9899:2018标准定义了该函数的安全版本memcpy_s


参数:
void * restrict s1

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

const void * restrict s2

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

size_t n

复制的字符数。


返回值:

函数返回s1的值。


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

#include <stdio.h>
#include <string.h>

int main(void)
{
    const char source[] = "All for one, one for all.";
    size_t length = strlen(source) + 1;
    char destination[length];

    memcpy(destination, source, length);
    for(size_t i=0; i<length; ++i)
        printf("%c", destination[i]);
    
    return 0;
}


输出:

All for one, one for all.


相关内容:
memmove 移动内存区域字符序列的函数。
strcpy 复制字符串的函数。
strncpy 从字符串中复制限定数量字符的函数。