clearing a char array c
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);
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.
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.