首页 > 编程知识 正文

sthaboutfunctionstrdup

时间:2023-05-06 07:22:00 阅读:258631 作者:1810

As now I was using the fundtion strdup very often, so that I want to say sth about it,  and I think that it just a function that combines the functions malloc and strcpy.

  用法:#include <string.h>

 功能:复制字符串s    说明:返回指向被复制的字符串的指针,所需空间由malloc()分配且可以由free()释放。    举例:           // strdup.c             #include <syslib.h>       #include <string.h>         main()       {         char *s="this is just f";         char *d;                 d=strdup(s);         printf("%s",d);           getchar();         return 0;       }

strdup()主要是拷贝字符串s的一个副本,由函数返回值返回,这个副本有自己的内存空间,和s不相干。

char *strdup(const char *s)
{
        char *t = NULL;
        if (s && (t = (char*)malloc(strlen(s) + 1)))
        strcpy(t, s);
        return t;
}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。

  • 相关阅读