栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ 中strcpy标准写法实例详解

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ 中strcpy标准写法实例详解

strcpy标准写法

实例代码:

// CppReference.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
using namespace std;


char *strcpy_v1(char *dest , const char *src)
{
  //调试时,使用断言,入口检测
  assert( (dest!=NULL) && (src!=NULL) );
  
  //注意这里的内存指向参数dest所在的内存,不是栈内存,因而可以在函数中返回
  char *to = dest;
  
  //主要操作在while条件中完成
  while( (*dest++ = *src++)!='')
  {
    NULL;  
  }
  
  //返回拷贝字符串首地址,方便连缀,比如strlen(strcpy(dest,"hello"))
  return to;
}


char *strcpy_v2(char *dest , const char *src)
{
  char *d = dest;
  char c;
  
  while((c=*src++) != '')
  {
    *(dest++)=c;
  }
  
  *dest='';
  
  return d;
}


char *strcpy_v2_error(char *dest , const char *src)
{
  char *d = dest;
  char c;
  
  while((c=*src++) != '')
  {
    *(d++)=c;
  }
  
  *d='';
  
  return d;
}



char *strcpy_v3(char *dest , const char *src)
{
  char *d = dest;
  char c;
  
  while(*src)
    *dest++ = *src++;
    
  *dest='';
  
  return d;
}


char *strcpy_v4(char *dest , const char *src)
{
  char *d = dest;
  char c;
  
  while( (*dest = *src)!='')
  {
    src++;
    dest++; 
  }
    
  *dest='';
  
  return d;
}


char *strcpy_v5(char* _restrict dest , const char* _restrict src)
{
  char *d = dest;
  char c;
  
  while( (*dest = *src)!='')
  {
    src++;
    dest++; 
  }
    
  *dest='';
  
  return d;
}


char *strcpy_v6(char* _restrict dest , const char* _restrict src)
{
  char *d = dest;
  char c;
  
  while(*dest++=*src++); 
  return d;
}



int _tmain(int argc, _TCHAR* argv[])
{
  char buf[512];
  
  char *buf2 = (char *)calloc(50,sizeof(char));
  
  char *buf3 = (char *)malloc(50*sizeof(char));
  
  char *buf5 = (char *)malloc(50*sizeof(char));
  
  char *buf6 = (char *)malloc(50*sizeof(char));
  
  printf("using strcpy_v1,the string 'Hello,World''s length is : %dn",strlen(strcpy_v1(buf,"Hello,World")));
  
  printf("using strcpy_v2,the string 'This is the best age''s length is : %dn",strlen(strcpy_v2(buf2,"This is the best age")));
  
  printf("using strcpy_v2,the string 'This is the best age''s length is : %dn",strlen(strcpy_v2_error(buf2,"This is the best age")));
  
  printf("using strcpy_v3,the string 'This is the best age''s length is : %dn",strlen(strcpy_v3(buf3,"This is the best age")));
  
  printf("using strcpy_v5,the string 'This is the best age''s length is : %dn",strlen(strcpy_v5(buf5,"This is the best age")));
  
  printf("using strcpy_v6,the string 'This is the best age''s length is : %dn",strlen(strcpy_v6(buf6,"This is the best age")));
 
  system("pause");
  
  return 0;
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/63538.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号