Chinaunix首页 | 论坛 | 博客
  • 博客访问: 712844
  • 博文数量: 134
  • 博客积分: 3207
  • 博客等级: 中校
  • 技术积分: 1995
  • 用 户 组: 普通用户
  • 注册时间: 2009-04-01 20:47
文章分类

全部博文(134)

文章存档

2022年(1)

2020年(7)

2018年(2)

2016年(5)

2015年(14)

2014年(21)

2013年(3)

2012年(1)

2011年(15)

2010年(30)

2009年(35)

分类: C/C++

2009-04-03 14:36:42

首先来看一个程序:

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

int main(int argc, char **argv)
{
    char a[30] = "1234567890";
    char b[30] = "abcdef\0ghijklmn";
    int i;
    printf("a[]=");
    for(i = 0; i < 30; i++)
        printf("%c", a[i]);
    printf("\n");


    strncpy(a, b, 20);
    printf("strncpy():a[]=");
    for(i = 0; i < 30; i++)
        printf("%c", a[i]);
    printf("\n");


    memcpy(a, b, 20);

    printf("memcpy():a[]=");
    for(i = 0; i < 30; i++)
        printf("%c", a[i]);
    printf("\n");
    return 0;
}


在运行完之后我们会得到以下结果:

a[]=1234567890

strncpy():a[]=abcdef

memcpy():a[]=abcdefhijklmn

很明显我们就得出了strncpy与memcpy的区别:

当遇到\0时,strncpy停止复制,而memcpy会继续复制.



阅读(1051) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~