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.
Updated: 01/31/2019 by Computer Hope. The abbreviation char is used as a reserved keyword in some programming languages, such as C, C++, C#, and Java. It is short for character, which is a data type that holds one character (letter, number, etc.) of data.
If you want to "empty" it in the sense that when it's printed, nothing will be printed, then yes, just set the first char to `\0'.
The code: char *p = new char[200]; p[100] = '\0'; delete[] p; is perfectly valid C++.
You need to copy the string into another, not read-only memory buffer and modify it there. Use strncpy() for copying the string, strlen() for detecting string length, malloc() and free() for dynamically allocating a buffer for the new string. Show activity on this post. The malloc needs 1 more byte.
If you want to zero out the whole array, you can:
memset(word, 0, sizeof(word));
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'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With