memcpy和strcpy的区别

1.memcpy函数

原型: void *memcpy(void *dest, const void *src, size_t n)
作用:把指针src指向的内存内容的前n个字节拷贝到指针dest指向的内存中,拷贝内存和数据类型无关,指针指向的内存包含的各种数据结构都能拷贝;

1.1.memcpy拷贝字符串数据:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main ()
{
    char srcName[]="Cristiano Ronaldo";
    printf("%s\n",srcName);
    
    char destName1[100];
    memcpy(destName1,srcName,sizeof(srcName)+1);
    printf("%s\n",destName1);
    
    char *destName2;
    destName2 = malloc(100);
    memcpy(destName2,srcName,sizeof(srcName)+1);
    printf("%s\n",destName2);
    free(destName2);

  return 0;
}

1.2 memcpy整个结构体

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    typedef struct student_info_s
    {
        int stuID;
        char *name;
        int math;
    }STUDENT_INFO_S;

    STUDENT_INFO_S studentA;
    studentA.stuID = 100;
    studentA.name = (char *)(void*) "Cristiano Ronaldo";
    studentA.math = 98;

    STUDENT_INFO_S* pstudentB;
    pstudentB = (STUDENT_INFO_S*)malloc(sizeof(STUDENT_INFO_S));
    if (NULL == pstudentB)
        return -1;

    memcpy(pstudentB, &studentA, sizeof(studentA));

    printf("After copy: studentID = %d,name = %s,math score = %d\n", pstudentB->stuID, pstudentB->name, pstudentB->math);
    
    free(pstudentB);
    return 0;
}

2. strcpy函数

原型:char* strcpy (char* dest, const char* src);
返回值:dest地址
作用:将"src"中的字符串按字符拷贝到'dest'中,遇到'0x00'时结束函数,返回"dest"地址

2.1 strcpy函数拷贝字符串

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main ()
{
    const char srcName[]="Cristiano Ronaldo";
    printf("%s\n",srcName);
    
    char destName1[100];
    strcpy(destName1,srcName);
    printf("%s\n",destName1);
    
  return 0;
}

posted on 2022-10-12 10:21  轩邈、  阅读(103)  评论(0编辑  收藏  举报

导航