字符串函数strdup
来源:互联网 发布:秒领棒棒糖软件 编辑:程序博客网 时间:2024/06/05 16:40
/* 字符串函数strdup,将串拷贝到新建的位置处 ,返回指向被复制的字符串指针
所需空间由malloc分配,且可以由free自由释放
/************************************************************************/
#include<iostream>
#include<malloc.h>
#include<assert.h>
using namespace std;
char *Strdup(const char *strSource)
{
assert(strSource!=NULL);//断言
char *address,*temp;
char *record;
int len=0;
record=(char *)strSource;//保存源字符串的地址
while(*record!='\0')//遍历源字符串,获取其长度
{
record++;
len++;
}
temp=(char *)malloc(len+1);//分配len+1空间
address=temp;//保存地址
while(*strSource!='\0')//将源字符串赋给temp
{
*temp=*strSource;
strSource++;
temp++;
}
*temp='\0';//末尾置'\0'
return address;
}
int main()
{
char *dup_str;
char *string1="abcde";
dup_str=Strdup(string1);
cout<<dup_str;
free(dup_str);//使用完Strdup后要用free释放
return 0;
}
strcpy与strdup的区别:
strdup可以直接把要复制的内容复制给没有初始化的指针,因为它会自动分配空间给目的指针;strdup内部在堆上创建了一个备份,所以即使没有看到malloc也应该在使用完毕后手动释放free
strcpy的目的指针一定是已经分配内存的指针
- 字符串函数strdup
- strdup函数
- strdup() 函数
- strdup函数
- strdup函数
- strdup函数
- strdup函数
- strdup函数
- 函数strdup()
- strdup函数
- strdup函数
- 系统函数C字符串的实现(5):strdup
- C语言 - strdup()函数复制字符串的实现
- strdup函数 -- linux函数
- strdup -- 复制字符串
- strdup() - 复制字符串
- strdup函数简介
- strdup函数简介
- Win7 系统还原被管理员禁用
- 线程池
- python自动单元测试框架
- linux 配置nginx 配置。
- comet 方法大集合 一看就懂
- 字符串函数strdup
- github参考
- win7 安装oracle11g
- php学习 第六十二节
- 在Linux下搭建ftp服务器
- broadcast, aidl和Content Provider的区别和适用场所?
- 为什么将实参Foo** 赋给形参Foo const**时出错。
- php学习 第六十三节
- ASP.NET 中FileUpload与UpdatePanel共用时FileUpload无法取到文件名信息