clearing a char array c
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.
Solution 1:
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.
Solution 2:
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:
memset(&arr[0], 0, sizeof(arr));
This is generally the fastest way to take care of this. If you can use C++, consider std::fill instead:
char *begin = &arr;
char *end = begin + sizeof(arr);
std::fill(begin, end, 0);
Solution 3:
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.
Solution 4:
Use:
memset(my_custom_data, 0, sizeof(my_custom_data));
Or:
memset(my_custom_data, 0, strlen(my_custom_data));