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/.

  • 4
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

源代码杀手

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值