常用库函数编程实现用法总结(四)strdup strtok itoa atoi

/*************************************************
函数名: strdup
功 能: 将串拷贝到新建的位置处
用 法: char *strdup(char *str);
这个函数在linux的man手册里解释为:
The strdup() function returns a pointer toa new string which is a
duplicate of the string s. Memory for the new string is obtained with
malloc(), and can be freed with free().The strndup() function is similar,
but onlycopies at most n characters. If s is longer than n,
only n characters are copied, and a terminating NUL is added.
Allocates enough storage via malloc() for a copy of the string, copies the
string into the new memory, and returns a pointer to it.
头文件: <stdlib.h>
strdup()主要是拷贝字符串s的一个副本,由函数返回值返回,
这个副本有自己的内存空间,和s不相干。strdup函数复制一个字符串,
使用完后要记得删除在函数中动态申请的内存,strdup函数的参数不能为NULL,
一旦为NULL,就会报段错误,因为该函数包括了strlen函数,而该函数参数不能是NULL
复制字符串,返回指向被复制字符串的指针。所需空间由malloc()分配,
且可以由free()释放。需要注意的是,在调用完这个函数后,一定要记得释放内存空间。
**************************************************/




char * my_strdup(const char *str)
{
    char *p;
    if (!str)
        return(NULL);
    if (p = malloc(my_strlen(str) + 1))
        return(my_strcpy(p,str));
    return(NULL);
}


char * __strdup (const char *s)
{
    size_t len =strlen (s) + 1;
    void *new =malloc (len);
    if (new == NULL)
        return NULL;
    return (char *)memcpy (new, s, len);
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
unsigned int Test()
{
    cha
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值