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

来源:互联网 发布:淘宝美瞳店铺哪个好 编辑:程序博客网 时间:2024/06/05 10:57

拷贝函数一般首选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
原创粉丝点击