zoukankan      html  css  js  c++  java
  • C语言 memcpy

    C语言 memcpy

    #include <string.h>
    void *memcpy(void *dest, const void *src, size_t n);

    功能:拷贝src所指的内存内容的前n个字节到dest所值的内存地址上。
    参数:

    • dest:目的内存首地址
    • src:源内存首地址,注意:dest和src所指的内存空间不可重叠
    • n:需要拷贝的字节数

    返回值:dest的首地址

    案例

    #define _CRT_SECURE_NO_WARNINGS
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <math.h>
    #include <time.h>
    
    int main(void)
    {
        // 1、数组拷贝
        // 内存拷贝
        int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
        int* p = (int*)malloc(sizeof(int) * 10);
        // 实现栈空间数据拷贝到堆空间
        // memcpy(目标, 源, 字节);
        memcpy(p, arr, sizeof(int) * 10);
        // 打印输出
        for (int i = 0; i < 10; i++)
        {
            printf("%d
    ", p[i]);
        }
        // 释放内存
        free(p);
    
        // 2、字符串
        // 内存拷贝
        char ch[] = "hello world";
        char str[100];
        // 拷贝:到停止
        strcpy(str, ch);
        printf("%s
    ", str);
        // 内存拷贝:拷贝内容与字节有关
        memcpy(str, ch, 13);
        printf("%s
    ", str);
    
        // 3、拷贝内存重叠
        // 如果拷贝的目标和源发生重叠,可能报错
        int arr2[] = { 1,2,3,4,5,6,7,8,9,10 };
        memcpy(&arr2[5], &arr2[3], 20);
        for (int i = 0; i < 10; i++)
        {
            printf("%d
    ", arr2[i]);
        }
    
        return 0;
    }
    memcpy 使用案例
  • 相关阅读:
    Node.js 0.12: 正确发送HTTP POST请求
    pm2 常用命令
    IntelliJ IDEA Configuring projects
    socket.io入门整理教程
    幂等函数
    Linux 下 ps 命令
    Linux 下 tail 命令
    Linux下chmod命令
    Linux下ll命令与ls -l
    Thrift——初学
  • 原文地址:https://www.cnblogs.com/xiangsikai/p/12379901.html
Copyright © 2011-2022 走看看