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] = \
set the first element to NULL. printing the char array will give you nothing back.
How about the following:
bzero(my_custom_data,40);
Writing a null character to the first character does just that. If you treat it as a string, code obeying the null termination character will treat it as a null string, but that is not the same as clearing the data. If you want to actually clear the data you'll need to use memset.
Nope. All you are doing is setting the first value to '\0' or 0.
If you are working with null terminated strings, then in the first example, you'll get behavior that mimics what you expect, however the memory is still set.
If you want to clear the memory without using memset, use a for loop.
Why would you think setting a single element would clear the entire array? In C, especially, little ever happens without the programmer explicitly programming it. If you set the first element to zero (or any value), then you have done exactly that, and nothing more.
When initializing you can set an array to zero:
char mcd[40] = {0}; /* sets the whole array */
Otherwise, I don't know any technique other than memset, or something similar.
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.