• strncpy 引起的思考,重新认识了strncpy这个函数【转】



    首先来看一个司空见惯的c语言列子:
    #include <stdio.h>
    #include <string.h>

    int main()
    {
        unsigned char arry[] = {0x00,0x01,0x02,0x03};
        unsigned char dest[] = {0xff,0xff,0xff,0xff};

        strncpy(dest,arry,sizeof(arry));

        printf("dest[0] is %X ",dest[0]);
        printf("dest[1] is %X ",dest[1]);
        printf("dest[2] is %X ",dest[2]);
        printf("dest[3] is %X ",dest[3]);

        return 0;
    }

    运行后发现了:
    dest[0] is 0
    dest[1] is 0
    dest[2] is 0
    dest[3] is 0
    原来的数组中的数据怎么没有了?

    傻眼了吧,就是这个问题困扰了我一个下午。不过最后感觉不对,可以用memcpy来完事。随后用memcpy代替,果然问题没有再出现。原来的数组中的数据依次被赋值为新的源地址数值。
    百思不得其解,回家后打开电脑查看了一下strncpy原代码。发现了问题:

    char* strncpy(char *dest, const char *src, size_t n)
    {
        size_t i;

        //Note 1:
        for (i = 0 ; i < n && src[i] != '' ; i++)
            dest[i] = src[i];
        //Note 2:
        for ( ; i < n ; i++)
            dest[i] = '';

        return dest;
    }

    Note 1:
    假设我们的源目的地址第一个字符为NULL (),那么第一个for循环立即返回。但是这个时候i取值为0。
    Note 2:
    随即进入第二个for循环,别忘了,i=0。那么在第二个for循环中巴dest第dest[1]个开始以后所有的数据都赋值为。

    第二个for循环的本意是(当拷贝大小size n大于源字符串长度时候)把前面若干个字符拷贝后剩下的最后所有的字符格式化为。

    原来是这样,好久没有用libc和string类的库函数了。突然这么一次还真是冷不丁的卡壳了。

    记录下来,也算是为工作和学习做一次笔记。
  • 相关阅读:
    String和enum的互相转换
    LeetCode: Sort Colors
    LeetCode: Subsets II
    LeetCode: Spiral Matrix II
    LeetCode: Subsets
    LeetCode: Sum Root to Leaf Numbers
    LeetCode: Sqrt(x)
    LeetCode: Sudoku Solver
    LeetCode: Spiral Matrix
    LeetCode: Substring with Concatenation of All Words
  • 原文地址:https://www.cnblogs.com/sky-heaven/p/5567503.html
Copyright © 2020-2023  润新知