C 标准库 - <string.h>

C 语言 strncpy() 函数用于复制字符串,但最多复制 n 个字符,用于安全地复制指定长度的字符串。

原型

char *strncpy(char *destination, const char *source, size_t n);

参数

  • destination - 目标数组;
  • source - 源字符串;
  • n - 最多复制的字符数。

返回值

返回 destination 的指针。

示例

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

int main()
{
    char src[] = "Hello World!";
    char dst[6];

    strncpy(dst, src, 5);
    dst[5] = '\0';  // 手动补上结尾符
    printf("dst = %s\n", dst);

    return 0;
}

输出:

dst = Hello

注意事项

strncpy 在源串不足 n 时用 \0 补齐;但源串长度 ≥ n 时不会自动补 \0,务必手动保证目标以 \0 结尾。