开发者

How to add a null character to the end of a string?

I start of with a

memcpy(g->db_cmd,l->db.param_value.val,l->db.param_value开发者_如何学Go.len);

which contains the value "function" however I want a null character to be appended like "function'\0'" I've tried a

memcpy(&g->db_cmd[l->db.param_value.len],0,1);

This crashes the program. I've tried memset also

 memset(&g->db_cmd[l->db.param_value.len],0,1);

This doesnt work. Any idea?


g->db_cmd[l->db.param_value.len] = 0;

assuming you have allocated space for that.


First off, C (and C++) is not dynamic like you know it from Java, C#, PHP and others. When you are presented with a string in C, the string is pretty much static in length.

To make the answer simpler, lets redefine your variables:

  • g->db_cmd will be called dest,
  • l->db.param_value.val will be called src, and
  • l->db.param_value.len will be called len.

You should allocate a new string of size len plus one (for the extra null).

Allocate a new dest:

dest = calloc(sizeof(char), len + 1);

calloc allocates an array of chars as long as len plus one. After calloc() has allocated the array it fills it with nulls (or \0) thus you automatically will have a null appended to your deststring.

Next, copy the src to dest with strncpy:

 strncpy(dest, src, len);

To convert this back to your variable names:

g->db_cmd = calloc(sizeof(char), l->db.param_value.len + 1);
strncpy(g->db_cmd, l->db.param_value.val, l->db.param_value.len);


If you want string-copying semantics, why not use a string-copying function?


Strings are by default null-terminated.
If you want a to ad an extra NULL at the end you can write "String\0"
or db_cmd[len]='\0'


If the source you're copying from also contains a NULL terminated string use

memcpy( g->db_cmd, l->db.param_value.val, l->db.param_value.len + 1 );

Otherwise you'll have to add the terminator yourself.

g->db_cmd[l->db.param_value.len] = '\0';

Of course, you need to ensure that the destination has enough room for this character.


memcpy takes two pointers, and an integer. In the lines that you say are crashing, you pass it a pointer, and two integers. The code cannot dereference the second argument (0).
If you really really want to use memcpy, you have to have a pointer to a zero

char zero = 0;
memcpy(&g->db_cmd[l->db.param_value.len], &zero , 1);

But I would really suggest pyroscope's answer. It's faster, and clearer.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜