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\n",dest[0]);
    printf("dest[1] is %X\n",dest[1]);
    printf("dest[2] is %X\n",dest[2]);
    printf("dest[3] is %X\n",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] != '\0' ; i++)
        dest[i] = src[i];
    //Note 2:
    for ( ; i < n ; i++)
        dest[i] = '\0';

    return dest;
}

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

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

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

记录下来,也算是为工作和学习做一次笔记。









本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/sky-heaven/p/5567503.html ,如需转载请自行联系原作者
相关文章
|
9天前
|
安全 C语言 C++
【C语言】超详解strncpy&&strncat&&strncmp&&strerror&&perror的使⽤和模拟实现
【C语言】超详解strncpy&&strncat&&strncmp&&strerror&&perror的使⽤和模拟实现
|
9天前
|
C语言
【C语言】字符串函数strcpy&&strcat&&strcmp&&strstr的使⽤和模拟实现2
【C语言】字符串函数strcpy&&strcat&&strcmp&&strstr的使⽤和模拟实现
|
12天前
|
存储 C语言
【C语言】字符串函数strcpy&&strcat&&strcmp&&strstr的使⽤和模拟实现1
【C语言】字符串函数strcpy&&strcat&&strcmp&&strstr的使⽤和模拟实现
|
7月前
|
编译器 Linux C语言
【C语言】字符串函数的介绍二( strcmp、strncpy、strncat、strncmp)
【C语言】字符串函数的介绍二( strcmp、strncpy、strncat、strncmp)
36 0
|
8月前
|
C语言
【C语言进阶】-- 重点字符串函数内存函数及其模拟实现(strlen,strcmp,strcat...memcpy,memmove)
【C语言进阶】-- 重点字符串函数内存函数及其模拟实现(strlen,strcmp,strcat...memcpy,memmove)
|
8月前
|
算法 C语言
你应该知道的C语言干货(4)(strncpy,strncmp,strncat,strstr,strtok)
该库函数作用和strcpy很相似,不同点在于
45 0
你应该知道的C语言干货(4)(strncpy,strncmp,strncat,strstr,strtok)
|
9月前
|
C语言
strcat函数和strncat函数--【C语言】
strcat函数和strncat函数--【C语言】
|
9月前
|
存储
strcpy函数与strncpy函数
strcpy函数与strncpy函数
|
10月前
|
编译器 C语言
C语言strlen,strcpy ,strcat, strcmp,strstr常用库函数的理解与模拟实现
C语言strlen,strcpy ,strcat, strcmp,strstr常用库函数的理解与模拟实现
101 0
|
11月前
|
C语言
C语言中基础(有关数据拷贝的函数,例:strcpy,strncpy,memcpy,memove库函数的实现和应该注意的小细节)
C语言中基础(有关数据拷贝的函数,例:strcpy,strncpy,memcpy,memove库函数的实现和应该注意的小细节)