问题描述
什么是的strdup的目的(c)中
功能?
推荐答案
这听起来像(假设你已经习惯了在C和UNIX分配字的简写方式)究竟是什么,它重复字符串。
Exactly what it sounds like (assuming you're used to the abbreviated way in which C and UNIX assigns words), it duplicates strings.
在牢记它实际上不是ISO C标准本身(这是一个POSIX的东西),它有效地做同样为以下code的一部分:
Keeping in mind it's actually not part of the ISO C standard itself (it's a POSIX thing), it's effectively doing the same as the following code:
char *strdup (const char *s) {
char *d = malloc (strlen (s) + 1); // Space for length plus nul
if (d == NULL) return NULL; // No memory
strcpy (d,s); // Copy the characters
return d; // Return the new string
}
在换句话说:
- 它试图分配足够的内存来保存旧的字符串(加一个空字符标记字符串的结束)。
- 如果分配失败,它集
错误号
到ENOMEM
并返回NULL
立即(错误号
设置为ENOMEM
的东西的malloc
这样做,我们并不需要明确地做它在我们的的strdup
)。 - 否则,分配工作,所以我们老的字符串复制到新的字符串,返回新的地址(主叫方负责在某一点释放)。
- It tries to allocate enough memory to hold the old string (plus a null character to mark the end of the string).
- If the allocation failed, it sets
errno
toENOMEM
and returnsNULL
immediately (setting oferrno
toENOMEM
is somethingmalloc
does so we don't need to explicitly do it in ourstrdup
). - Otherwise the allocation worked so we copy the old string to the new string and return the new address (which the caller is responsible for freeing at some point).
请记住这是概念性的定义。正在使用的任何图书馆的作家值得他们的薪水可能提供高度优化的code针对特定的处理器。
Keep in mind that's the conceptual definition. Any library writer worth their salary may have provided heavily optimised code targeting the particular processor being used.
如果您在功能痛恨多个出口(我不知道,除非它影响可读性,我不认为是这样的短暂功能的情况下)的人群的一部分,你可以写code作为:
If you're part of the crowd that abhors multiple exit points in functions (I don't unless it affects readability, which I don't believe to be the case for such a short function), you can write the code as:
char *strdup (const char *s) {
char *d = malloc (strlen (s) + 1); // Allocate memory
if (d != NULL) strcpy (d,s); // Copy string if okay
return d; // Return new memory
}
这篇关于的strdup() - 这是什么在C呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!