问题描述
当我要将 src_str
复制到 dst_arr
时,我应该使用什么?为什么?
char dst_arr [10];
char * src_str =hello;
PS:我的头比我的电脑的磁盘旋转得更快好或坏是 strncpy
和 strlcpy
。
注意:我知道 strlcpy
无法在任何地方使用。
strncpy
是一个用于非终止的固定宽度字符串的函数。更确切地说,其目的是将零终止字符串转换为非终止固定宽度字符串(通过复制)。换句话说, strncpy
在这里没有意义。 这里真正的选择是 strlcpy
和纯文本 strcpy
。
(即可能被截断)复制到 dst_arr
,正确的函数使用 strlcpy
。
对于 dst_ptr
...没有这样的事情复制到 dst_ptr
。您可以复制到 dst_ptr
指向的内存,但首先必须确保它指向某处并分配该内存。有很多不同的方法来做到。
例如,您可以使 dst_ptr
指向 dst_arr
,在这种情况下,答案与以前的情况相同 - strlcpy
。
可以使用 malloc
分配内存。如果你分配的内存量足够保证足够的字符串(即至少 strlen(src_str)+ 1
字节被分配),那么你可以使用plain strcpy
或甚至 memcpy
来复制字符串。在这种情况下,没有必要也没有理由使用 strlcpy
,虽然有些人可能更喜欢使用它,因为它不知何故给他们额外的安全感。
如果你有意分配更少的内存(即你希望你的字符串被截断),那么 strlcpy
成为正确的函数。 / p>
what should I use when I want to copy src_str
to dst_arr
and why?
char dst_arr[10];
char *src_str = "hello";
PS: my head is spinning faster than the disk of my computer after reading a lot of things on how good or bad is strncpy
and strlcpy
.
Note: I know strlcpy
is not available everywhere. That is not the concern here.
strncpy
is never the right answer when your destination string is zero-terminated. strncpy
is a function intended to be used with non-terminated fixed-width strings. More precisely, its purpose is to convert a zero-terminated string to a non-terminated fixed-width string (by copying). In other words, strncpy
is not meaningfully applicable here.
The real choice you have here is between strlcpy
and plain strcpy
.
When you want to perform "safe" (i.e. potentially truncated) copying to dst_arr
, the proper function to use is strlcpy
.
As for dst_ptr
... There's no such thing as "copy to dst_ptr
". You can copy to memory pointed by dst_ptr
, but first you have to make sure it points somewhere and allocate that memory. There are many different ways to do it.
For example, you can just make dst_ptr
to point to dst_arr
, in which case the answer is the same as in the previous case - strlcpy
.
Or you can allocate the memory using malloc
. If the amount of memory you allocated is guaranteed to be enough for the string (i.e. at least strlen(src_str) + 1
bytes is allocated), then you can use the plain strcpy
or even memcpy
to copy the string. There's no need and no reason to use strlcpy
in this case , although some people might prefer using it, since it somehow gives them the feeling of extra safety.
If you intentionally allocate less memory (i.e. you want your string to get truncated), then strlcpy
becomes the right function to use.
这篇关于strncpy或strlcpy在我的情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!