当前位置: 首页 > news >正文

C语言使用技巧(六):memcpy函数为数组、函数变量和结构体内部的数组赋值

1、单一变量的赋值

源码:

#include <stdio.h>

#include <string.h>

struct s1
{
    char *name;
    int age;
}stu1 = {"kangchou", 25};

void main(void)
{
    struct s1 s2;
    memcpy(&s2, &stu1, sizeof(stu1));
    printf("s2.name = %s\ns2.age = %d\n", s2.name, s2.age);
    getch();
}

执行结果:

在这里插入图片描述

2、字符串数组的赋值的覆盖

将一个数组的前几个元素覆盖另一个数组的前几个元素。

下面解决了常见报错的问题;error: ‘for’ loop initial declarations are only allowed in C99 mode

源码:

#include <stdio.h>

#include<string.h>

int main()
{
    char a[4] = "mmmm";
    char b[7] = "123455";
    memcpy(b, a, 3);
    printf("%d\n\r", sizeof(b));
    printf("%s\n", b);

    int i;
    for(i = 0; i < sizeof(b); i++)
    {
        printf("b[%d]的字符串是%c\n\r", i, b[i]);
    }
    getch();
    return 0;
}

执行结果:
在这里插入图片描述

3、给整形数组赋值也可以全部覆盖:

#include <stdio.h>
#include <string.h>
#include <stdint.h>
int main()
{
    int i;
    int a[4] = {1, 2, 3, 100};
    int b[3] = {4, 5, 6};
    memcpy(b, a, 4);               // 通常int = 4 * char, 所以复制的结果为b = {1, 5, 6}, 只复制了前4个char地址的内容
    memcpy(b, a, sizeof(int) * 3); // 这里的sizeof(int) * 3 == 12, 所以复制结果为b = {1, 2, 3};
    for (i = 0; i < 3; i++)
    {
        printf("%d ", b[i]);
    }
    getch();
    return 0;
}

执行结果:1 2 3

4、memcpy()二维数组拷贝

源码:


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void printarr2d(int (*a)[3], int row, int col);

/************************************************/
void printarr2d(int (*a)[3], int row, int col)
{
    int i, j;
    for (i = 0; i < row; i++)
    {
        for (j = 0; j < col; j++)
        {
            printf("%d ", a[i][j]);
        }
        printf("\n");
    }
}

int main()
{
    int i, j;
    int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
    int b[4][3] = {{0, 0, 0}, {0, 0, 0}};
    memcpy(b[2], a, sizeof(int) * 2 * 3);
    printarr2d(b, 4, 3);
    getch();
    return 0;
}

执行结果:
在这里插入图片描述

5、给结构体中的数组赋值

源码:

#include <stdio.h>

#include <string.h>

struct s1
{
    char *name;
    int age[2]; //memcpy给该数组赋值
}stu1 = {"kangchou", {25,24}};//初始化结构体变量

void main(void)
{
    struct s1 s2;
    memcpy(&s2, &stu1, sizeof(stu1));
    printf("s2.name = %s\ns2.age = %d\n", s2.name, s2.age[1]);
    getch();
    return 0;
}

执行结果:
在这里插入图片描述

6、附录:

ubuntu ->man men 附录memcpy函数用法:

C语言复制函数分为3种,strcpy,strncpy,memcpy,适用场景如下:
strcpy:字符串复制
strncpy:相同结构的指针数组复制
memcpy:对象复制,指针结构可以不同,指向的数组结构必须相

MEMCPY(3)                                                              Linux Programmer's Manual                                                             MEMCPY(3)

NAME
       memcpy - copy memory area

SYNOPSIS
       #include <string.h>

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

DESCRIPTION
       The memcpy() function copies n bytes from memory area src to memory area dest.  The memory areas must not overlap.  Use memmove(3) if the memory areas do over‐
       lap.

RETURN VALUE
       The memcpy() function returns a pointer to dest.

ATTRIBUTES
       For an explanation of the terms used in this section, see attributes(7).

       ┌──────────┬───────────────┬─────────┐
       │Interface │ Attribute     │ Value   │
       ├──────────┼───────────────┼─────────┤
       │memcpy()  │ Thread safety │ MT-Safe │
       └──────────┴───────────────┴─────────┘
CONFORMING TO
       POSIX.1-2001, POSIX.1-2008, C89, C99, SVr4, 4.3BSD.

NOTES
       Failure to observe the requirement that the memory areas do not overlap has been the source of real bugs.  (POSIX and the C standards are explicit that employ‐
       ing  memcpy()  with  overlapping  areas  produces  undefined  behavior.)   Most notably, in glibc 2.13 a performance optimization of memcpy() on some platforms
       (including x86-64) included changing the order in which bytes were copied from src to dest.

       This change revealed breakages in a number of applications that performed copying with overlapping areas.  Under the  previous  implementation,  the  order  in
       which  the  bytes  were  copied had fortuitously hidden the bug, which was revealed when the copying order was reversed.  In glibc 2.14, a versioned symbol was
       added so that old binaries (i.e., those linked against glibc versions earlier than 2.14) employed a memcpy() implementation that safely handles the overlapping
       buffers case (by providing an "older" memcpy() implementation that was aliased to memmove(3)).

SEE ALSO
       bcopy(3), memccpy(3), memmove(3), mempcpy(3), strcpy(3), strncpy(3), wmemcpy(3)

COLOPHON
       This  page  is  part of release 4.04 of the Linux man-pages project.  A description of the project, information about reporting bugs, and the latest version of
       this page, can be found at http://www.kernel.org/doc/man-pages/.

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 赶快收藏:快速安装PyTorch和TensorFlow(gpu+cpu+1.7.1+2.2.0--cuda_11.0.2_450.51.05)命令
  • 2004年7月13日
  • Matlab使用笔记(十一):simulink模型仿真的时序数据类:timeseries
  • simulink中调用C语言进行仿真
  • 网站完工
  • 2021年完美安装YOLO教程:成功在Windows10下安装YOLO开发环境并成功完成目标检测测试「基于C/C++版本」
  • 2004年7月15日
  • Python使用高德地图绘制经纬度坐标位置
  • 2021年最新完整统计TensorFlow2.x报错记录与解决方法「希望能帮助到你」
  • 2004年7月16日
  • Release of the Data Access Application Block 3.1
  • 【长篇博文】Docker学习笔记与深度学习环境的搭建和部署(一)
  • 两个小时学会DirectDraw编程 (转载)
  • 【长篇博文】Docker学习笔记与深度学习环境的搭建和部署(二)
  • 从系统中取得指定资源图像(转载)
  • ----------
  • .pyc 想到的一些问题
  • 【EOS】Cleos基础
  • 【知识碎片】第三方登录弹窗效果
  • bootstrap创建登录注册页面
  • create-react-app做的留言板
  • CSS实用技巧
  • gcc介绍及安装
  • iOS 系统授权开发
  • JavaScript设计模式系列一:工厂模式
  • JavaScript新鲜事·第5期
  • Java编程基础24——递归练习
  • Python打包系统简单入门
  • Theano - 导数
  • uni-app项目数字滚动
  • Vue.js 移动端适配之 vw 解决方案
  • 机器人定位导航技术 激光SLAM与视觉SLAM谁更胜一筹?
  • 算法-图和图算法
  • 我的zsh配置, 2019最新方案
  • 小李飞刀:SQL题目刷起来!
  • 学习笔记TF060:图像语音结合,看图说话
  • CMake 入门1/5:基于阿里云 ECS搭建体验环境
  • 大数据全解:定义、价值及挑战
  • # 计算机视觉入门
  • #pragma once与条件编译
  • #每日一题合集#牛客JZ23-JZ33
  • #我与Java虚拟机的故事#连载09:面试大厂逃不过的JVM
  • (02)Hive SQL编译成MapReduce任务的过程
  • (2024最新)CentOS 7上在线安装MySQL 5.7|喂饭级教程
  • (Pytorch框架)神经网络输出维度调试,做出我们自己的网络来!!(详细教程~)
  • (Spark3.2.0)Spark SQL 初探: 使用大数据分析2000万KF数据
  • (多级缓存)缓存同步
  • (附源码)ssm旅游企业财务管理系统 毕业设计 102100
  • (附源码)计算机毕业设计ssm电影分享网站
  • (六)什么是Vite——热更新时vite、webpack做了什么
  • (三十五)大数据实战——Superset可视化平台搭建
  • (十八)Flink CEP 详解
  • (十五)使用Nexus创建Maven私服
  • (算法)前K大的和
  • (五)activiti-modeler 编辑器初步优化