ANSI C - Clearing a string

混江龙づ霸主 提交于 2019-12-05 04:45:37

问题


I've got a string declared like this:

str=malloc(sizeof(char)*128);

I want to clear it completely so that whenI do strncat() operation, the new characters will be written to the beginning of str. The reason I need to clear it is that I'm writing over it with a simplified version of itself (deleting excess whitespace).


回答1:


I suggest you simply do this:

*str = '\0';

You don't need to clear the entire contents of the buffer. You can just set the first char to zero and then you have the empty string.




回答2:


Use memset:

memset(str, 0, sizeof(char)*128);

Regardless of this, if you are writing the string over itself, you shouldn't use strcat - the objects that you copy must not overlap:

If copying takes place between objects that overlap, the behavior is undefined.

and a string definitely overlaps with itself.

Removing whitespace from a string can be easily achieved with a simple function:

void remove_space(char* r) {
    char *w = r;
    do { *w = *r++; w += *w && !isspace(*w); } while (*w);
}



回答3:


You would like to use calloc instead of plain malloc?

Something like

calloc(128, sizeof(char));

EDIT Also, strncat doesn't require you having a null terminated string at the destination. Just make sure that the destination is large enough to hold the concatenated resulting string, including the additional null-character.

And as dasblinkenlight notes, do not copy overlappingly with strncat. Consider using normal dst[i++] = src[j++] way of copying.



来源:https://stackoverflow.com/questions/10193777/ansi-c-clearing-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!