How to zero out a char array? 
Author Message
 How to zero out a char array?

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?

Thanks,



Thu, 03 Mar 2005 11:05:20 GMT  
 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?

>Thanks,

memset( sData, 0, sizeof( sData ) );


Thu, 03 Mar 2005 11:16:33 GMT  
 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++



Fri, 04 Mar 2005 05:09:20 GMT  
 
 [ 3 post ] 

 Relevant Pages 

1. How to zero out a char array?

2. Differences between char array[SIZE] and char *array

3. Converting char array of literals chars to escape chars

4. A char pointer (char *) vs. char array question

5. char array (array of array...) question

6. Char* array to Unsigned Char*

7. char pointer to 2D char array

8. char* to char array[] ?

9. char arrays versus char strings.

10. Passing a char array[n] to a function expecting a char*

11. arrays and pointers, char * vs. char [], distinction

12. Checksums of a.outs

 

 
Powered by phpBB® Forum Software