zoukankan      html  css  js  c++  java
  • strncpy和memcpy

    strcpy strncpy

    memcpy

    #include <string.h>

    char *strncpy(char *restrict s1, const char *restrict s2, size_t n);

    DESCRIPTION       

    The  strncpy()  function shall copy not more than n bytes (bytes that follow a null byte are not copied) from the array pointed to by s2 to the array pointed to by s1.  If copying takes place between objects that overlap, the behavior is undefined.If the array pointed to by s2 is a string that is shorter than n bytes, null bytes shall be appended to the copy in the array pointed  to by s1, until n bytes in all are written.

    RETURN VALUE       

    The strncpy() function shall return s1; no return value is reserved to indicate an error.

    #include<string.h>
    int main(int agrn,char *agrc[])
    {
    char dest[1024] = {0};
    char *src="Hello,Wrold";
    strncpy(dest,src,
    sizeof(dest)-1);
    dest[
    1024-1] = 0;
    return 0;
    }


    SYNOPSIS       #include <string.h>
    void *memcpy(void *restrict s1, const void *restrict s2, size_t n);
    DESCRIPTION       

    The  memcpy()  function  shall copy n bytes from the object pointed to by s2 into the object pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.

    RETURN VALUE       

    The memcpy() function shall return s1; no return value is reserved to indicate an error.

    #include<string.h>
    #include
    <iostream>
    using namespace std;
    struct Object
    {
    char name[255];
    void print()
    {
    cout
    <<"Name:"<<name;
    }
    };
    struct Test:public Object
    {
    int id;
    short sex;
    };
    int main(int agrn,char*agrc[])
    {
    Test obj1;
    strncpy(obj1.name,
    "Liuda",sizeof(obj1.name));
    obj1.name[
    sizeof(obj1.name)-1] = 0;
    obj1.id
    = 123;
    obj1.sex
    = 0;
    Test obj2;
    memcpy(
    &obj2,&obj1,sizeof(obj1));
    obj2.print();
    return 0;
    }

    在来说说他们的区别。

    strncpy复制n个,但是,他毕竟是字符串函数,所以碰到\0,就不复制了。

    memcpy就不是,他一定会复制n个字节的数据。

  • 相关阅读:
    MFC Bitmap::FromBITMAPINFO返回空问题
    String成员函数
    用xshell连接l自己的inux
    回调函数
    文件操作相关函数(POSIX 标准 open,read,write,lseek,close)
    Linux_GDB调试学习笔记
    程序中的一些限制(基于Linux系统C语言)
    第10课:[实战] Redis 网络通信模块源码分析(3)
    第09课:【实战】Redis网络通信模块源码分析(2)
    简单模拟多段线绘制Pline命令过程的撤销功能
  • 原文地址:https://www.cnblogs.com/xloogson/p/2097064.html
Copyright © 2011-2022 走看看