John Marston
John Marston

Reputation: 12269

Clearing contents of a fixed char array in C++ after value has been assigned

Hi i have the following code:

char msg[10000];
string mystr = "hello";
// stores mystr into msg
copy(mystr.begin(), mystr.end(), msg);

After the code copies, i want to clear the contents of char msg[10000]. How do i do that?

Upvotes: 2

Views: 8566

Answers (3)

Some programmer dude
Some programmer dude

Reputation: 409186

If you truly want to clear the whole array, then using memset as suggested by Andrew is the way to do it. However, if you just want to make sure that as a string it gets zero length, it's enough to clear only the first entry:

msg[0] = '\0';

Upvotes: 2

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507015

Using modern facilities

std::array<char, 10000> msg;

string mystr = "hello";
// stores mystr into msg
copy(mystr.begin(), mystr.end(), msg.begin());

// then clear it again
msg = {{}};

Not sure why you wanna copy it first and then clear it, but that's how you can do it. Without C++11 generalized initializers, you can say

msg = std::array<char, 10000>();

Of course, you can always use boost::array instead std::array, it works the same.

Upvotes: 6

Andrew
Andrew

Reputation: 24846

char msg[10000];
memset(msg, 0, 10000);

if you know the size of filled data:

memset(msg, 0, SizeOfFilledData);

Upvotes: 1

Related Questions