strncpy 订阅
strncpy函数用于将指定长度的字符串复制到字符数组中,是 C语言的库函数之一,来自 C语言标准库,定义于 string.h。语法形式为:char *strncpy(char *dest, const char *src, int n),表示把src所指向的字符串中以src地址开始的前n个字节复制到dest所指的数组中,并返回被复制后的dest。 [1-2] 展开全文
strncpy函数用于将指定长度的字符串复制到字符数组中,是 C语言的库函数之一,来自 C语言标准库,定义于 string.h。语法形式为:char *strncpy(char *dest, const char *src, int n),表示把src所指向的字符串中以src地址开始的前n个字节复制到dest所指的数组中,并返回被复制后的dest。 [1-2]
信息
头文件
string.h
属    于
库函数
适    用
电脑编程
来    自
C语言标准库
中文名
strncpy
功    能
串拷贝
外文名
strncpy
strncpystrncpy基本格式
char *strncpy(char *destinin, char *source, int maxlen);destinin:表示复制的目标字符数组;source:表示复制的源字符数组;maxlen:表示复制的字符串长度。 [3] 
收起全文
精华内容
下载资源
问答
  • strncpy

    2020-05-25 20:47:22
    strncpy 原型 char * strncpy(char * dest, char * src, size_t n); 作用:将src前n个字符放入deset所指空间中. 打印函数如下: void print_string(char * c , int n) { for(int i = 0 ; i < n ; i++) { if(c[i...

    strncpy

    原型

    char * strncpy(char  *  dest, char  * src, size_t  n);
    

    作用:将src前n个字符放入deset所指空间中.

    打印函数如下:

    void print_string(char * c , int n)
    {
        for(int i = 0 ; i < n ; i++)
        {
    	if(c[i] == '\0')
    	{
    	    cout << "NULL";
    	}
    	cout << c[i] << ' ';
        }
    }
    

    以下所说len(char * c)包含’\0’.

    当len(deset)>=len(src):

    若n=(0,src长度),也就是1len(src)-1的时候,就是将src中前1len(src)-1的字符复制给dest.没有将’\0’复制过去,所以需要开始就把dest初始化为’\0’.

    演示如下:

    int main()
    {
        char array1[10];
        
        memset(array1 , '\0' , sizeof(array1));
        strncpy(array1, "1234" ,4);
        print_string(array1,10);
        
        cout << endl;
        
    	    memset(array1 , '\0' , sizeof(array1));
        strncpy(array1, "1234" ,3);
        print_string(array1,10);
        
        cout << endl;
        return 0;
    }
    

    结果:
    在这里插入图片描述

    若n=len(src),相当于将包括’\0’整个src复制到dest中,所以最后一位是’\0’,这个例子为了方便,将一开始的字符数组都初始化为’\0’了.

    演示如下:

    int main()
    {
        char array1[10];
        memset(array1 , '\0' , sizeof(array1));
        strncpy(array1, "1234" ,sizeof("1234"));
        print_string(array1,10);
        cout << endl;
    }
    

    结果:
    在这里插入图片描述

    若n=len(dest),也是将src包含’\0’复制到dest中,dest剩余大小自动设置为’\0’.

    int main()
    {
        char array1[10];
        strncpy(array1, "1234" ,sizeof(array1));
        print_string(array1,10);
        cout << endl;
        return 0;
    }
    

    结果:
    在这里插入图片描述

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YGJX3ATt-1590332768259)(2019-12-28_16-40.png)]

    当len(dest) < len(src)

    一般是把len(dest)长度的src复制过去,然后将最后一位换成’\0’.

    综上,如果想把尽可能多的src中的字符复制到dest中,一般将n设为len(dest),然后把最后以为换成’\0’,就可以避免很多问题,也不用一开始把dest设置为’\0’.

    举例:

    int main()
    {
         char array1[10];
        strncpy(array1, "1234" ,sizeof(array1));
        array1[9]='\0';
        print_string(array1,strlen(array1));
    
        cout << endl;
    
        strncpy(array1, "123456789005465123" ,sizeof(array1));
        array1[9]='\0';
        print_string(array1,strlen(array1));
    
        cout << endl;
        
        return 0;
    }
    

    结果:

    在这里插入图片描述

    展开全文
  • strncpy 

    2009-08-13 00:10:00
    strncpy char * strncpy(char *s1,char *s2,size_t n); 将字符串s2中最多n个字符复制到字符数组s1中,返回指向s1的指针。 注意:如果源串长度大于n,则strncpy不复制最后的/0结束符,所以是不安全的,复制完后...

    strncpy

      char * strncpy(char *s1,char *s2,size_t n);
      将字符串s2中最多n个字符复制到字符数组s1中,返回指向s1的指针。
      注意:如果源串长度大于n,则strncpy不复制最后的'/0'结束符,所以是不安全的,复制完后需要手动添加字符串的结束符才行。
      Strcpy和Strncpy的区别- -
      第一种情况:
      char* p="how are you ?";
      char name[20]="ABCDEFGHIJKLMNOPQRS";
      strcpy(name,p); //name改变为"how are you ? "====>正确!
      strncpy(name,p,sizeof(name)); //name改变为"how are you ? " ====>正确!
      第二种情况:
      char* p="how are you ?";
      char name[10];
      strcpy(name,p); //目标串长度小于源串,错误!
      name[sizeof(name)-1]='/0'; //和上一步组合,弥补结果,但是这种做法并不可取,因为上一步出错处理方式并不确定
      strncpy(name,p,sizeof(name)); //源串长度大于指定拷贝的长度sizeof(name),注意在这种情况下不会自动在目标串后面加'/0'
      name[sizeof(name)-1]='/0'; //和上一步组合,弥补结果
      ================================================
      总结:strcpy
      源字串全部拷贝到目标字串中,包括'/0',但是程序员必须保证目标串长度足够,且不与源串重叠。
      strncpy
      如果目标长>=指定长>源长,则将源串全部拷贝到目标串,连同'/0'
      如果指定长<源长,则将截取源串中按指定长度拷贝到目标字符串,不包括'/0'
      如果指定长>目标长,错误!
    展开全文
  • strncpy warnings

    2021-01-02 10:01:29
    readstat/readstat_writer.c:82:9: warning: ‘strncpy’ output truncated before terminating nul copying as many bytes from a string as its length [-Wstringop-truncation] readstat/readstat_writer.c:261...
  • 二、strncpy _Count表示Source的长度 三、strcpy_s 这里是将source中所有的内容都复制到destination中,所以_SizeInBytes==len(_Source);不然会出错,也就是多了不行,少了也不行 四、strncpy_s 这里要求_...

    一、strcpy
    在这里插入图片描述
    Dest和Source的长度需要一样大
    二、strncpy
    在这里插入图片描述
    _Count表示Source的长度
    三、strcpy_s
    在这里插入图片描述
    这里是将source中所有的内容都复制到destination中,所以_SizeInBytes==len(_Source);不然会出错,也就是多了不行,少了也不行

    在这里插入图片描述
    在这里插入图片描述
    四、strncpy_s
    在这里插入图片描述
    这里要求_MaxCount == _SizeInBytes;//因为在复制完前_MaxCount 个source后会在Destination的第_SizeInBytes中,也就是最后一个赋值为’\0’;
    如果_MaxCount < _SizeInBytes-1中间会复制?
    在这里插入图片描述
    在这里插入图片描述
    否则异常;

    展开全文
  • strncpy, strncpy_s

    2018-08-08 11:06:00
    Defined in header<string.h> (1) char*strncpy(char*dest,constchar*src,size_tcount); (until C99) char*strncpy(char*restrictdest,const...
    Defined in header <string.h>
       
      (1)  
    char *strncpychar *dest, const char *src, size_t count );
    (until C99)
    char *strncpychar *restrict dest, const char *restrict src, size_t count );
    (since C99)
    errno_t strncpy_s(char *restrict dest, rsize_t destsz,
                      const char *restrict src, rsize_t count);
    (2) (since C11)
         
    1) Copies at most count characters of the character array pointed to by src (including the terminating null character, but not any of the characters that follow the null character) to character array pointed to by dest.
     If count is reached before the entire array src was copied, the resulting character array is not null-terminated.
     If, after copying the terminating null character from srccount is not reached, additional null characters are written to dest until the total of count characters have been written.
     The behavior is undefined if the character arrays overlap, if either dest or src is not a pointer to a character array (including if dest or src is a null pointer), if the size of the array pointed to by dest is less than count, or if the size of the array pointed to by src is less than count and it does not contain a null character.
    2) Same as (1), except that the function does not continue writing zeroes into the destination array to pad up to count, it stops after writing the terminating null character (if there was no null in the source, it writes one at dest[count] and then stops). Also, the following errors are detected at runtime and call the currently installed constraint handler function:
    • src or dest is a null pointer
    • destsz or count is zero or greater than RSIZE_MAX
    • count is greater or equal destsz, but destsz is less or equal strnlen_s(src, count), in other words, truncation would occur
    • overlap would occur between the source and the destination strings
     The behavior is undefined if the size of the character array pointed to by dest < strnlen_s(src, destsz) <= destsz; in other words, an erroneous value of destsz does not expose the impending buffer overflow. The behavior is undefined if the size of the character array pointed to by src < strnlen_s(src, count) < destsz; in other words, an erroneous value of count does not expose the impending buffer overflow.
    As with all bounds-checked functions, strncpy_s is only guaranteed to be available if __STDC_LIB_EXT1__ is defined by the implementation and if the user defines __STDC_WANT_LIB_EXT1__ to the integer constant 1 before including string.h.

    Parameters

    dest - pointer to the character array to copy to
    src - pointer to the character array to copy from
    count - maximum number of characters to copy
    destsz - the size of the destination buffer

    Return value

    1) returns a copy of dest
    2) returns zero on success, returns non-zero on error. Also, on error, writes zero to dest[0] (unless dest is a null pointer or destsz is zero or greater than RSIZE_MAX) and may clobber the rest of the destination array with unspecified values.

    Notes

    As corrected by the post-C11 DR 468, strncpy_s, unlike strcpy_s, is only allowed to clobber the remainder of the destination array if an error occurs.

    Unlike strncpystrncpy_s does not pad the destination array with zeroes, This is a common source of errors when converting existing code to the bounds-checked version.

    Although truncation to fit the destination buffer is a security risk and therefore a runtime constraints violation for strncpy_s, it is possible to get the truncating behavior by specifying count equal to the size of the destination array minus one: it will copy the first count bytes and append the null terminator as always: strncpy_s(dst, sizeof dst, src, (sizeof dst)-1);

    Example

    #define __STDC_WANT_LIB_EXT1__ 1
    #include <string.h>
    #include <stdio.h>
    #include <stdlib.h>
     
    int main(void)
    {
        char src[] = "hi";
        char dest[6] = "abcdef"; // no null terminator
        strncpy(dest, src, 5); // writes five characters 'h', 'i', '\0', '\0', '\0' to dest
        printf("strncpy(dest, src, 5) to a 6-byte dest gives : ");
        for(size_t n = 0; n < sizeof dest; ++n) {
            char c = dest[n];
            c ? printf("'%c' ", c) : printf("'\\0' ");
        }
     
        printf("\nstrncpy(dest2, src, 2) to a 2-byte dst gives : ");
        char dest2[2];
        strncpy(dest2, src, 2); // truncation: writes two characters 'h', 'i', to dest2
        for(size_t n = 0; n < sizeof dest2; ++n) {
            char c = dest2[n];
            c ? printf("'%c' ", c) : printf("'\\0' ");
        }
        printf("\n");
     
    #ifdef __STDC_LIB_EXT1__
        set_constraint_handler_s(ignore_handler_s);
        char dst1[6], src1[100] = "hello";
        int r1 = strncpy_s(dst1, 6, src1, 100);      // writes 0 to r1, 6 characters to dst1
        printf("dst1 = \"%s\", r1 = %d\n", dst1,r1); // 'h','e','l','l','o','\0' to dst1
     
        char dst2[5], src2[7] = {'g','o','o','d','b','y','e'};
        int r2 = strncpy_s(dst2, 5, src2, 7);        // copy overflows the destination array
        printf("dst2 = \"%s\", r2 = %d\n", dst2,r2); // writes nonzero to r2,'\0' to dst2[0]
     
        char dst3[5];
        int r3 = strncpy_s(dst3, 5, src2, 4);        // writes 0 to r3, 5 characters to dst3
        printf("dst3 = \"%s\", r3 = %d\n", dst3,r3); // 'g', 'o', 'o', 'd', '\0' to dst3 
    #endif
    }

    Possible output:

    strncpy(dest, src, 5) to a 6-byte dst gives : 'h' 'i' '\0' '\0' '\0' 'f'
    strncpy(dest2, src, 2) to a 2-byte dst gives : 'h' 'i'
    dst1 = "hello", r1 = 0
    dst2 = "", r2 = 22
    dst3 = "good", r3 = 0

    References

    • C11 standard (ISO/IEC 9899:2011):
    • 7.24.2.4 The strncpy function (p: 363-364)
    • K.3.7.1.4 The strncpy_s function (p: 616-617)
    • C99 standard (ISO/IEC 9899:1999):
    • 7.21.2.4 The strncpy function (p: 326-327)
    • C89/C90 standard (ISO/IEC 9899:1990):
    • 4.11.2.4 The strncpy function

     

     

    From: https://en.cppreference.com/w/c/string/byte/strncpy

    转载于:https://www.cnblogs.com/time-is-life/p/9441567.html

    展开全文
  • strncpy函数

    2020-08-19 17:32:26
    char *strncpy(char *destinin, char *source, int maxlen) ; 参数 destinin:表示复制的目标字符数组; source:表示复制的源字符数组; maxlen:表示复制的字符串长度 注意:strncpy函数所需要的3个参数是两个...
  • C++中strncpy函数和strncpy_s函数的使用及注意事项

    万次阅读 多人点赞 2018-09-17 17:49:24
    在掌握了strcpy函数和strcpy_s函数之后,我们不可避免地会谈到strncpy函数和strncpy_s函数,其实这四个函数的功能几乎一致,就是对两个字符串数组进行复制和赋值,但是具体实现有一点点区别。 首先来说一下strncpy...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 3,802
精华内容 1,520
关键字:

strncpy