拷贝函数的选取,极其sizeof()运算符的注意事项及其实例

17 篇文章 0 订阅

拷贝函数一般首选memcpy()函数

  • 有长度限制,安全可靠
  • 拷贝内容无限制,可以拷贝任意内容,例如字符、数组、整形、结构体、类等。

拷贝字符串函数尽量选择带长度参数的比较安,如strncpy(),尽量不使用strcpy()

strcpy和memcpy()主要有以下3方面的区别
  • 拷贝的内容strcpy()只能复制字符串,memcpy()可以拷贝任意内容,例如字符数组、整型、结构体、类等。

  • 复制的方法:memcpy()第3个参数决定拷贝的长度,处理好不容易溢出。strcpy不需要指定长度遇到被复制字符串的结束符”\0”才结束,所以容易溢出。

  • 用途不同:通常strcpy()类函数只能用来拷贝字符串,而memcpy()能复制其他类型数据

sizeof运算符

sizeof运算符计算出来的字符数组如,char str[] = “hello”的字节数sizeof(str)=6,不是字符串的实际长度(字节数),sizeof计算出的字符串包含“\0”,所以在进行定义时就需要把“\0”算入,进行字符拷贝时,要注意对“\0”的处理,默认是拷入“\0”的。
具体可以看看下面的实例** — sizeof()实例

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

int main()
{
    char a[]="hello";
    char buff[20];
    memset(buff,0,sizeof(buff));

    printf("buff = %d\n",sizeof(buff));//buff = 20
    printf("a = %d\n",sizeof(a));//a = 6

    strncpy(buff,a,sizeof(a) - 1);//将实际长度hello拷贝到buff中,不包含\0
    printf("buff = %s\n",buff);//buff = hello

    strncpy(buff, a, sizeof(buff) - 1);//为了安全防止溢出
    printf("buff = %s",buff);//buff = hello
    return 0;

}

memcpy()实例

作用:将str中的字符串拷贝到字符数组dst中。

#include <stdio.h>
#include <string.h>
int main()
{
    char *str="GoldenGlobalView";
    char dst[20];
    memcpy(dst,str,(strlen(s)+1));
    printf("%s a = %d",d,sizeof(str));//a =4
    getchar();
    return 0;
}

作用:将str中第13个字符开始的4个连续字符拷贝到dst中。(从0开始)

#include <string.h>
#include <stdio.h>
int main()
{
    char* str="GoldenGlobalgood";
    char dst[20];
    memcpy(dst,str+12,4);//从第13个字符(V)开始复制,连续复制4个字符(good)
    dst[4]='\0';//memcpy(dst,str+12*sizeof(char),4*sizeof(char));也可
    printf("%s",dst);
   getchar();
   return 0;
}

作用:拷贝后覆盖原有部分数据

#include<stdio.h>
#include<string.h>
int main(void)
{
    char *src="******************************";
    char dst[]="abcdefghijklmnopqrstuvwxyz0123456";
    printf("dst before memcpy:%s\n",dst);
    memcpy(dst,src,strlen(src));
    printf("dst after memcpy:%s\n",dst);
    //运行结果:dst after memcpy:******************************456
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值