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.
Why not use
memset()
? That's how to do it.Setting the first element leaves the rest of the memory untouched, but str functions will treat the data as empty.
Pls find below where I have explained with data in the array after case 1 & case 2.
Case 1:
Result:
Case 2:
Result:
Though setting first argument to NULL will do the trick, using memset is advisable
You should use memset. Setting just the first element won't work, you need to set all elements - if not, how could you set only the first element to 0?