
How to zero out a char array?
Quote:
>I have,
>char sData[128];
>strcpy(sData,"dadadadadadada");
>printf("%s\n",sData);
>Know I want to zero out the character array. How is this correctly done?
>*sData=NULL; // is this correct?
No. Conceptually, NULL is a null pointer constant, but in reality,
it's required to be some integer constant equal to zero in C++. You
can freely assign it to other arithmetic types, and though
conceptually wrong, the above will compile. However, you should only
use NULL to mean "null pointer constant". Many people just use 0 for
their null pointer constant, because NULL is longer to type, may
impart some false sense of safety, and requires one to #include one of
the standard headers which #defines it.
So, lets write it as follows:
*sData = 0;
That sets sData[0] to zero, which makes it a valid nul-terminated
string. It has zero length, but it hasn't been zeroed out. To
accomplish the latter, you can use memset:
memset(sData,0,sizeof(sData));
Note that sizeof(sData) works only because sData is an array. Were it
a pointer into an array, you'd zero out sizeof(char*) bytes, which
might be too many or too few. Thus, when dealing with pointers,
instead of sizeof, you must explicitly pass the size.
--
Doug Harrison
Microsoft MVP - Visual C++