与memcpy串联 [英] Concatenate with memcpy
问题描述
我正在尝试使用memcpy将两个字符串添加在一起.我需要第一个memcpy包含数据.但是第二个没有添加.知道为什么吗?
I'm trying to add two strings together using memcpy. The first memcpy does contain the data, I require. The second one does not however add on. Any idea why?
if (strlen(g->db_cmd) < MAX_DB_CMDS )
{
memcpy(&g->db_cmd[strlen(g->db_cmd)],l->db.param_value.val,strlen(l->db.param_value.val));
memcpy(&g->db_cmd[strlen(g->db_cmd)],l->del_const,strlen(l->del_const));
g->cmd_ctr++;
}
推荐答案
size_t len = strlen(l->db.param_value.val);
memcpy(g->db_cmd, l->db.param_value.val, len);
memcpy(g->db_cmd + len, l->del_const, strlen(l->del_cost)+1);
这将为您带来以下好处:
This gains you the following:
- 减少对
strlen
的冗余调用.每个字符串都必须遍历该字符串,因此最好将这些调用减至最少. - 第二个
memcpy
需要实际添加,而不是替换.因此,第一个参数必须与上一个调用不同. - 请注意第二个
memcpy
的第三个arg中的+1
.那是针对NUL终结者的.
- Less redundant calls to
strlen
. Each of those must traverse the string, so it's a good idea to minimize these calls. - The 2nd
memcpy
needs to actually append, not replace. So the first argument has to differ from the previous call. - Note the
+1
in the 3rd arg of the 2ndmemcpy
. That is for the NUL terminator.
我也不确定您的if
陈述是否有意义.也许更明智的做法是确保g->db_cmd
有足够的空间来存储您要复制的内容.您可以通过sizeof
(如果db_cmd
是字符数组)或通过跟踪堆分配量(如果通过malloc
获取db_cmd
)来做到这一点.因此,也许最有意义的是:
I'm not sure your if
statement makes sense either. Perhaps a more sane thing to do would be to make sure that g->db_cmd
has enough space for what you are about to copy. You would do that via either sizeof
(if db_cmd
is an array of characters) or by tracking how big your heap allocations are (if db_cmd
was acquired via malloc
). So perhaps it would make most sense as:
size_t param_value_len = strlen(l->db.param_value.val),
del_const_len = strlen(l->del_const);
// Assumption is that db_cmd is a char array and hence sizeof(db_cmd) makes sense.
// If db_cmd is a heap allocation, replace the sizeof() with how many bytes you
// asked malloc for.
//
if (param_value_len + del_const_len < sizeof(g->db_cmd))
{
memcpy(g->db_cmd, l->db.param_value.val, param_value_len);
memcpy(g->db_cmd + param_value_len, l->del_const, del_const_len + 1);
}
else
{
// TODO: your buffer is not big enough. handle that.
}
这篇关于与memcpy串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!