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.
An array in C is just a memory location, so indeed, your
my_custom_data[0] = '\0';
assignment simply sets the first element to zero and leaves the other elements intact.If you want to clear all the elements of the array, you'll have to visit each element. That is what
memset
is for:This is generally the fastest way to take care of this. If you can use C++, consider std::fill instead:
I usually just do like this:
That is not correct as you discovered
Exactly!
You need to use memset to clear all the data, it is not sufficient to set one of the entries to null.
However, if setting an element of the array to null means something special (for example when using a null terminating string in) it might be sufficient to set the first element to null. That way any user of the array will understand that it is empty even though the array still includes the old chars in memory
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:
Otherwise, I don't know any technique other than memset, or something similar.
Use:
Or: