Zeroing out a string
suggest changeYou can call memset
to zero out a string (or any other memory block).
Where str
is the string to zero out, and n
is the number of bytes in the string.
#include <stdlib.h> /* For EXIT_SUCCESS */ #include <stdio.h> #include <string.h> int main(void) { char str[42] = "fortytwo"; size_t n = sizeof str; /* Take the size not the length. */ printf("'%s'\n", str); memset(str, '\0', n); printf("'%s'\n", str); return EXIT_SUCCESS; }
Prints:
'fortytwo' ''
Another example:
#include <stdlib.h> /* For EXIT_SUCCESS */ #include <stdio.h> #include <string.h> #define FORTY_STR "forty" #define TWO_STR "two" int main(void) { char str[42] = FORTY_STR TWO_STR; size_t n = sizeof str; /* Take the size not the length. */ char * point_to_two = strstr(str, TWO_STR); printf("'%s'\n", str); memset(point_to_two, '\0', n); printf("'%s'\n", str); memset(str, '\0', n); printf("'%s'\n", str); return EXIT_SUCCESS; }
Prints:
'fortytwo' 'forty' ''
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents