ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# C `strncpy()`函数 > 原文: [https://beginnersbook.com/2017/11/c-strncpy-function/](https://beginnersbook.com/2017/11/c-strncpy-function/) **`strncpy()`函数**类似于[`strcpy()`函数](https://beginnersbook.com/2017/11/c-strcpy-function/),不同之处在于它只从源字符串复制指定数量的字符到目标字符串。 ## C `strncpy()`声明 ```c char *strncpy(char *str1, const char *str2, size_t n) ``` `str1` - 目标字符串。复制源字符串`str2`的前`n`个字符到其中的字符串。 `str2` - 源字符串 `n - 需要复制的源字符串的字符数。 ## `strncpy()`的返回值 在将源字符串的`n`个字符复制到其中之后,它返回指向目标字符串的指针。 ## 示例:`strncpy()`函数 ```c #include <stdio.h> #include <string.h> int main () { char str1[20]; char str2[25]; /* The first argument in the function is destination string. * In this case we are doing full copy using the strcpy() function. * Here string str2 is destination string in which we are copying the * specified string */ strcpy(str2, "welcome to beginnersbook.com"); /* In this case we are doing a limited copy using the strncpy() * function. We are copying only the 7 characters of string str2 to str1 */ strncpy(str1, str2, 7); printf("String str1: %s\n", str1); printf("String str2: %s\n", str2); return 0; } ``` 输出: ```c String str1: welcome String str2: welcome to beginnersbook.com ``` #### 相关文章: 1. [C - `strcoll()`函数](https://beginnersbook.com/2017/11/c-strcoll-function/) 2. [C - `strcmp()`函数](https://beginnersbook.com/2017/11/c-strcmp-function/) 3. [C - `strchr()`函数](https://beginnersbook.com/2017/11/c-strchr-function/) 4. [C - `strncat()`函数](https://beginnersbook.com/2017/11/c-strncat-function/)