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

memccpy函数


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

描述:

该函数将参数s2指向对象中的字符复制到参数s1指向的对象中,遇到以下两种情况之一复制过程将停止(以先发生者为准。):

1、首个出现的字符c(会转换为unsigned char类型。)已经被复制。

2、已经复制了n个字符。

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


参数:
void * restrict s1

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

const void * restrict s2

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

int c

int类型对象,会转换为unsigned char类型。

size_t n

复制的字符数。


返回值:

函数返回指向参数s1中被复制字符c之后的那个字符的指针;如果在参数s2的前n个字符中没有字符c,函数返回空指针。


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
/*函数memccpy范例*/

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

#define LENGTH 100

int main(void)
{
    const char source[] = "All for one, one for all.";
    char destination[LENGTH] = {0};
    int ch = 'r';
    void *ptr = NULL;

    ptr = memccpy(destination, source, (unsigned char)ch, LENGTH-1);
    if(ptr == NULL)
    {
        printf("The character '%c' was not found.\n", ch);
        printf("The character sequence written to array destination: \n");
        printf("%s\n", destination);
    }
    else
    {
        printf("The character '%c' was found.\n", ch);
        printf("The character sequence written to array destination: \n");
        printf("%s\n", destination);
    }
    
    return 0;
}


输出:

The character 'r' was found.

The character sequence written to array destination:

All for


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


主要参考资料:

1、ISO/IEC 9899:2024