nick_name
nick_name

Reputation: 1373

ANSI C - Clearing a string

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).

Upvotes: 2

Views: 9778

Answers (3)

Pavan Manjunath
Pavan Manjunath

Reputation: 28525

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.

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726539

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

Upvotes: 4

David Heffernan
David Heffernan

Reputation: 612944

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.

Upvotes: 13

Related Questions