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

strncpy函数


概要:
#include <string.h>
char *strncpy(char * restrict s1, 
      const char * restrict s2, 
      size_t n);

描述:

该函数从参数s2指向的数组复制不超过n个字符(空字符后的字符不会被复制。)到参数s1指向的数组中。如果参数s2指向的数组前n个字符中没有空字符,结果将没有终止空字符。

如果参数s2指向的数组是一个比n个字符短的字符串,参数s1指向数组写入复制内容后将添加空字符,直至写入n个字符。

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

ISO/IEC 9899:2018标准定义了该函数的安全版本strncpy_s


参数:
char * restrict s1

指向目标数组的指针,复制字符将存入该数组。

const char * restrict s2

指向源数组的指针,从该数组复制字符。

size_t n

最多复制的字符数。


返回值:

函数返回s1的值。


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
/*函数strncpy范例*/

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

int main(void)
{
    const char source[] = {'N', 'i', '\0', 'H', 'a', 'o', '\0'};
    char destination[10];

    strncpy(destination, source, 5);
    for(int i=0; i<5; ++i)
    {
        if(destination[i] == 0)
            puts("NUL");
        else
            printf("%c\n", destination[i]);
    }
    
    return 0;
}


输出:

N

i

NUL

NUL

NUL


相关内容:
memcpy 复制内存区域字符序列的函数。
memmove 移动内存区域字符序列的函数。
strcpy 复制字符串的函数。