在C语言中,你可以使用strdup
函数来简洁地分配一个缓冲区并将一个字符串复制到其中。但就我所知,对于一般的内存操作,没有类似的函数。例如,我无法像这样说:
TBD
struct myStruct *foo = malloc(sizeof(struct myStruct));
fill_myStruct(foo);
struct myStruct *bar = memdup(foo, sizeof(struct myStruct));
// bar is now a reference to a new, appropriately sized block of memory,
// the contents of which are the same as the contents of foo
那么我的问题有三个:
- 是否有一些像这样的标准库函数,我不知道吗?
- 如果没有,是否有一种简洁并且最好是标准的方法来完成这个任务,而不需要显式调用
malloc
和memcpy
? - C语言为什么包含
strdup
而不包含memdup
?
strdup
不就是一个malloc
和一个memcpy
吗? - Marlonmalloc()
和memcpy()
)。看起来有点微不足道,不值得为此写一个函数。如果你想避免字符串被多次遍历,strdup()
函数就会稍微复杂一些。 - Mysticialstrdup()
的实现不需要精确两次遍历输入字符串?(一次用来计算缓冲区大小,一次用来复制) - Billy ONealstruct myStruct *bar = (struct myStruct *)malloc(sizeof(struct myStruct)); memcpy(bar, foo, sizeof(struct myStruct));
转换成一个相对简短的单行代码,让人一眼就能明白正在发生什么。 - Danmalloc
的返回值进行类型转换。除此之外,C语言没有包含strdup
函数。不过,在POSIX系统中,该函数已经被广泛应用。但是不能保证它在所有系统上都可用。而struct myStruct *bar = malloc(sizeof *bar); *bar = *foo;
这种写法看起来还不错,对吧? - Daniel Fischer