Search code examples
cansi-c

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


Solution

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