zoukankan      html  css  js  c++  java
  • C语言memcpy函数的用法

    介绍

    memcpy是memory copy的缩写,意为内存复制,在写C语言程序的时候,我们常常会用到它。它的函原型如下:

    void *memcpy(void *dest, const void *src, size_t n);
    

    它的功能是从src的开始位置拷贝n个字节的数据到dest。如果dest存在数据,将会被覆盖。memcpy函数的返回值是dest的指针。memcpy函数定义在string.h头文件里。

    例子

    1.将一个字符串数据复制到一块内存。

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #define N 10
    int main(void)
    {
        char* target=(char*)malloc(sizeof(char)*N);
        memcpy(target,"0123456789",sizeof(char)*N);
        puts(target);
        free(target);
        return 0;
    }
    

    编译,运行,将输出:0123456789
    2.将一个字符串数据复制到一块内存的指定位置。

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #define N 10
    int main(void)
    {
        char* target=(char*)malloc(sizeof(char));
        for(int i=0;i<N;i++){
    	    memcpy(target+i,"a",sizeof(char));
        }
        puts(target);
        free(target);
    	return 0;
    }
    

    编译,运行,将输出:aaaaaaaaaa
    3.数据覆盖

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #define N 10
    int main(void)
    {
        char* target=(char*)malloc(sizeof(char)*N);
        memcpy(target,"0123456789",sizeof(char)*N);
        puts(target);
        memcpy(target,"aaaaa",sizeof(char)*(N-5));
        puts(target);
        free(target);
        return 0;
    }
    

    编译,运行,将输出:

    0123456789
    aaaaa56789
    
  • 相关阅读:
    《linux/unix设计思想》读后感
    webserver ZooKeeper Cluster
    OS + RedHat 6.3 x64 / sshd X11 /
    nGrinder SocketTest.groovy
    OS + Centos7.6 gdm / xmanager xstart
    OS + CentOS 7 / VirtualBox 6.0 / VMware-Workstation-Full-15.1.0
    浅谈MySQL Replication(复制)基本原理
    MySQL存储引擎比较
    explain SQL语句性能检测
    看看JavaScript中void(0)的含义
  • 原文地址:https://www.cnblogs.com/luoyesiqiu/p/10703271.html
Copyright © 2011-2022 走看看