memccpy
来自 cppreference.com
定义在头文件 <string.h> 中 |
||
void* memccpy( void* restrict dest, const void* restrict src, int c, size_t count ); |
(自 C23 起) | |
将 src 指向的对象中的字节复制到 dest 指向的对象中,在满足以下两个条件中的任意一个时停止
- 已复制 count 个字节
- 找到(并复制)字节 (unsigned char)c。
src 和 dest 对象被解释为 unsigned char 数组。
如果满足任何条件,行为未定义
- 访问超出 dest 数组的末尾;
- 对象重叠(这违反了 restrict 契约)
- dest 或 src 是无效的或空指针
内容 |
[编辑] 参数
dest | - | 指向要复制到的对象的指针 |
src | - | 指向要复制的对象的指针 |
c | - | 终止字节,首先转换为 unsigned char |
count | - | 要复制的字节数 |
[编辑] 返回值
如果找到字节 (unsigned char)c,则 memccpy
返回指向 dest 中 (unsigned char)c 之后下一个字节的指针。否则,它返回空指针。
[编辑] 备注
此函数与 POSIX memccpy
相同。
memccpy(dest, src, 0, count) 的行为类似于 strncpy(dest, src, count),除了前者返回指向写入缓冲区末尾的指针,并且不会用零填充目标数组。因此,memccpy
可用于有效地连接多个字符串。
char bigString[1000]; char* end = bigString + sizeof bigString; char* p = memccpy(bigString, "John, ", '\0', sizeof bigString - 1); if (p) p = memccpy(p - 1, "Paul, ", '\0', end - p); if (p) p = memccpy(p - 1, "George, ", '\0', end - p); if (p) p = memccpy(p - 1, "Joel ", '\0', end - p); if (!p) end[-1] = '\0'; puts(bigString); // John, Paul, George, Joel
[编辑] 示例
运行此代码
#include <ctype.h> #include <stdio.h> #include <string.h> int main(void) { const char src[] = "Stars: Altair, Sun, Vega."; const char terminal[] = {':', ' ', ',', '.', '!'}; char dest[sizeof src]; const char alt = '@'; for (size_t i = 0; i != sizeof terminal; ++i) { void* to = memccpy(dest, src, terminal[i], sizeof dest); printf("Terminal '%c' (%s):\t\"", terminal[i], to ? "found" : "absent"); // if `terminal` character was not found - print the whole `dest` to = to ? to : dest + sizeof dest; for (char* from = dest; from != to; ++from) putchar(isprint(*from) ? *from : alt); puts("\""); } puts("\n" "Separate star names from distances (ly):"); const char *star_distance[] = { "Arcturus : 37", "Vega : 25", "Capella : 43", "Rigel : 860", "Procyon : 11" }; char names_only[64]; char *first = names_only; char *last = names_only + sizeof names_only; for (size_t t = 0; t != (sizeof star_distance) / (sizeof star_distance[0]); ++t) { if (first) first = memccpy(first, star_distance[t], ' ', last - first); else break; } if (first) { *first = '\0'; puts(names_only); } else puts("Buffer is too small."); }
输出
Terminal ':' (found): "Stars:" Terminal ' ' (found): "Stars: " Terminal ',' (found): "Stars: Altair," Terminal '.' (found): "Stars: Altair, Sun, Vega." Terminal '!' (absent): "Stars: Altair, Sun, Vega.@" Separate star names from distances (ly): Arcturus Vega Capella Rigel Procyon
[编辑] 参见
(C11) |
将一个缓冲区复制到另一个缓冲区 (函数) |
(C95)(C11) |
在两个不重叠的数组之间复制一定数量的宽字符 (函数) |
(C11) |
将一个缓冲区移动到另一个缓冲区 (函数) |
(C11) |
将一个字符串复制到另一个字符串 (函数) |
(C11) |
连接两个字符串 (函数) |