C++ strncpy()

strncpy() 原型

char* strncpy( char* dest, const char* src, size_t count );

strncpy() 函数接受三个参数:dest、src 和 count。它将 src 指向的字符串最多 count 个字符复制到 dest 指向的内存位置。

如果 count 小于 src 的长度,则将 src 的前 count 个字符复制到 dest,并且不以 null 结尾。如果 count 大于 src 的长度,则将 src 的所有字符复制到 dest,并添加额外的终止 null 字符,直到总共写入 count 个字符。

如果字符串重叠,行为是未定义的。

它定义在 <cstring> 头文件中。

strncpy() 参数

  • dest:要将内容复制到的字符数组的指针
  • src:要从中复制内容的字符数组的指针。
  • count:要复制的最大字符数。

strncpy() 返回值

strncpy() 函数返回 dest,即指向目标内存块的指针。

示例:strncpy() 函数如何工作

#include <cstring>
#include <iostream>

using namespace std;

int main()
{
    char src[] = "It's Monday and it's raining";
    char dest[40];

    /* count less than length of src */
    strncpy(dest,src,10);
    cout << dest << endl;

    /* count more than length of src */
    strncpy(dest,src,strlen(src)+10);
    cout << dest << endl;
    return 0;
}

运行程序后,输出将是

It's Monday
It's Monday and it's raining

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战