ANSI C - Clearing a string

大兔子大兔子 提交于 2019-12-03 21:15:58

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.

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);
}
Pavan Manjunath

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.

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