strdup() - 它在C中做了什么?

本文翻译自:strdup() - what does it do in C?

C中strdup()函数的用途是什么?


#1楼

参考:https://stackoom.com/question/13l8/strdup-它在C中做了什么


#2楼

strdup() does dynamic memory allocation for the character array including the end character '\\0' and returns the address of the heap memory: strdup()为字符数组执行动态内存分配,包括结束字符'\\ 0',并返回堆内存的地址:

char *strdup (const char *s)
{
    char *p = malloc (strlen (s) + 1);   // allocate memory
    if (p != NULL)
        strcpy (p,s);                    // copy string
    return p;                            // return the memory
}

So, what it does is give us another string identical to the string given by its argument, without requiring us to allocate memory. 所以它的作用是给我们另一个与其参数给出的字符串相同的字符串,而不需要我们分配内存。 But we still need to free it, later. 但我们以后仍然需要释放它。


#3楼

char * strdup(const char * s)
{
  size_t len = 1+strlen(s);
  char *p = malloc(len);

  return p ? memcpy(p, s, len) : NULL;
}

Maybe the code is a bit faster than with strcpy() as the \\0 char doesn't need to be searched again (It already was with strlen() ). 也许代码比strcpy()快一点,因为\\0 char不需要再次搜索(它已经与strlen() )。


#4楼

strdup()函数是字符串重复的简写,它接受一个参数作为字符串常量或字符串文字,并为字符串分配足够的空间,并在分配的空间中写入相应的字符,最后返回分配的地址调用例程的空间。


#5楼

From strdup man : 来自strdup man

The strdup() function shall return a pointer to a new string, which is a duplicate of the string pointed to by s1 . strdup()函数应返回一个指向新字符串的指针,该字符串是s1指向的字符串的副本。 The returned pointer can be passed to free() . 返回的指针可以传递给free() A null pointer is returned if the new string cannot be created. 如果无法创建新字符串,则返回空指针。


#6楼

它通过运行传入的字符串的mallocstrcpy来传递传入的字符串的副本。malloc的缓冲区返回给调用者,因此需要在返回值上自由运行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值