开发者

Concatenate with Memcpy

I'm trying to concatenate two string and I cannot use strcpy and strcat, so I'm trying to do this through memcopy. However, on the third statement the memcpy it is not adding on to the con开发者_JAVA技巧tinuation of the first memcpy. Any idea how to do this?

memset(&l->db.param_key.param_name, ' ', sizeof(l->db.param_key.param_name));
memcpy(l->db.param_key.param_name,g->program_id_DB,(strlen(g->program_id_DB)));
memcpy(l->db.param_key.param_name[strlen(g->program_id_DB)+1],l->userId_const,sizeof(l->userId_const));


The address in the third invocation should be:

l->db.param_key.param_name + strlen(g->program_id_DB) + 1

Note that for T * p, the expression p[i]; is identical to *(p + i). You don't want to dereference, you want the address, so you just add to the pointer.

(It is also true that p + i is identical to &p[i] as long as i is a valid index.)

Also mind @Nobody's observation that your first line is incorrect and you should just say l->db.param_key.param_name (or equivalently &l->db.param_key.param_name[0]).


You are giving to the second memcpy the valye of the last array's element. The correct way is to give the address(with the ampersand operator (like it was implicitly meant in the second statement).

memcpy(&l->db.param_key.param_name[strlen(g->program_id_DB)+1],l->userId_const,sizeof(l->userId_const))


your codeexample is a little bit horrible, but

memset(l->db.param_key.param_name,0,sizeof(l->db.param_key.param_name));
memcpy(l->db.param_key.param_name,g->program_id_DB,strlen(g->program_id_DB));
memcpy(&l->db.param_key.param_name[strlen(g->program_id_DB)],l->userId_const,sizeof(l->userId_const));

should work, if l->db.param_key.param_name and l->userId_const are a char-arrays.


Use memcpy() exactly like strcpy() except you have to work with string size instead of string length.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜