strdup

The difference between strcpy() and strdup():

strcpy will not allocate the memory for the copy for you, which means you have to give it not only the pointer to the string to copy, but also a pointer to the place to copy it to, which you have set up yourself. strdup will grab itself a place to copy the string to, which you will have to free up later when you don't need the copy anymore.

函数名: strdup
功  能: 将串拷贝到新建的位置处
用  法: char *strdup(char *str);
程序例:

C/C++ code
#include  < stdio.h >  #include  < string .h >  #include  < alloc.h >  int  main( void ) {  char  * dup_str,  * string =  " abcde " ; dup_str  =  strdup( string ); printf( " %s\n " , dup_str); free(dup_str);  return  0 ; }


函数名: strcpy
功  能: 串拷贝
用  法: char *strcpy(char *str1, char *str2);
程序例:

C/C++ code
#include  < stdio.h >  #include  < string .h >  int  main( void ) {  char  string [ 10 ];  char  * str1  =  " abcdefghi " ; strcpy( string , str1); printf( " %s\n " ,  string );  return  0 ; }

************************************************

strdup不是标准的c函数,所以linux会报错!~
strcpy是标准的c函数,在windows里报错是因为指针没申请空间吧!~
可以先strlen判断from的大小,之后为to申请空间,之后再strcpy就不会报错了!~

*************************************************

 

strdup可以直接把要复制的内容复制给没有初始化的指针,因为它会自动分配空间给目的指针
strcpy的目的指针一定是已经分配内存的指针

*************************************************

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值