Reputation: 5425
I use a string:
char word[100];
I add some chars to each position starting at 0. But then I need be able to clear all those positions so that I can start add new characters starting at 0.
If I don't do that then if the second string is shorten then the first one I end up having extra characters from the first string when adding the second one since I don't overwrite them.
Upvotes: 9
Views: 50807
Reputation:
You could assign a null terminator to the first position of the char
array.
*word = '\0';
Upvotes: 1
Reputation: 422132
If you want to zero out the whole array, you can:
memset(word, 0, sizeof(word));
Upvotes: 24
Reputation: 19477
You don't need to clear them if you are using C-style zero-terminated strings. You only need to set the element after the final character in the string to NUL ('\0').
For example,
char buffer[30] = { 'H', 'i', ' ', 'T', 'h', 'e', 'r', 'e', 0 }; // or, similarly: // char buffer[30] = "Hi There"; // either example will work here. printf("%s", buffer); buffer[2] = '\0'; printf("%s", buffer)
will output
Hi There
Hi
even though it is still true that buffer[3] == 'T'
.
Upvotes: 12