How to clear data from a char array?

Title says it all, does anybody know how?
Last edited on
I guess you could do strcpy( myString, "" );.


What exactly do you mean by "clear data"?

Do you mean you want it to be an empty string? If so, you can use iHutch's method, or else set the first element to be '\0':

 
myString[0] = '\0';


Or do you mean that you want to set every element of the array to '\0'?

Or do you mean that you want to destroy a dynamically allocated array of characters so that the memory is released?

Or do you mean something else?
Last edited on
closed account (S6k9GNh0)
std::fill - The improved C++ alternative to memset.

http://www.cplusplus.com/reference/algorithm/fill/
Last edited on
do

1
2
3
4
for(int erase = 0;;erase++)
{
      array[erase] = '\n';
}


something like that, try it
^ that will put you into an infinite loop and crash your program. You might want to specify a condition like erase < int(array.length());
closed account (S6k9GNh0)
Or you could use built-in compiler-optimized functions to do your job like I specified. But what do I know...
lol, I made that thing in 5 sec and I didn't bother to check it
use this:

1
2
3
4
5
char str[] = "Hello";

for (int i = 0; i < sizeof(str); i++) {
        str[i] = '\0';
}
Last edited on
Please take personally: http://www.cplusplus.com/forum/beginner/1988/5/#msg20048

computerquip posted a perfectly valid solution that works in all cases. Please don't post additional solutions, especially if they don't work in all cases.
Last edited on
@Sadegh2007

sizeof (str) will not do exactly what you think it does. What it does it that is returns the size in bytes of each character in the string and adds them together. So to use sizeof, you have to divide by the size of one char to get you the number of characters in the string
iirc sizeof(char) == 1
I don't think that that's guaranteed.
I'm pretty sure the C++ standard does guarantee that.
That's in the very definition of the sizeof operator
ISO wrote:
sizeof(char), sizeof(signed char) and sizeof(unsigned char) are 1.
Last edited on
So what's all the talk about there being theoretical compilers with characters being 64 bits?
No problem with that, sizeof(char) == sizeof(int) == sizeof(long long) == 1 is valid
Wait, what? Why would sizeof(some_64_bit_type) == 1? I thought it was the number of bytes, not the number of native word sizes?
sizeof returns the number of bytes. C++ is valid for a platform where there are 64 bits in a byte (and one byte in a long long and one byte in a char). It's also valid for a platform with one's complement arithmetic and other impractical setups.

(to keep it less off-topic, I support std::fill)
Ah, I forgot that C++ supported a bits-per-byte different than 8.
Topic archived. No new replies allowed.