Chinaunix首页 | 论坛 | 博客
  • 博客访问: 53653
  • 博文数量: 104
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 10
  • 用 户 组: 普通用户
  • 注册时间: 2016-09-11 15:25
文章分类

全部博文(104)

文章存档

2016年(104)

我的朋友

分类: C/C++

2016-10-06 11:04:05

原文地址:strncpy与memcpy 作者:lanlovehua

首先来看一个程序:

#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会继续复制.



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