clearing a char array c

ant2009 picture ant2009 · Mar 11, 2009 · Viewed 392.3k times · Source

I thought by setting the first element to a null would clear the entire contents of a char array.

char my_custom_data[40] = "Hello!";
my_custom_data[0] = '\0';

However, this only sets the first element to null.

or

my_custom_data[0] = 0; 

rather than use memset, I thought the 2 examples above should clear all the data.

Answer

JaredPar picture JaredPar · Mar 11, 2009

It depends on how you want to view the array. If you are viewing the array as a series of chars, then the only way to clear out the data is to touch every entry. memset is probably the most effective way to achieve this.

On the other hand, if you are choosing to view this as a C/C++ null terminated string, setting the first byte to 0 will effectively clear the string.