What is the best way to reset a char [] in C?

I use the line:

char word[100]; 

I add several characters to each position, starting from 0. But then I need to clear all these positions so that I can start adding new characters, starting from 0.

If I do not, then if the second line is shortened, then the first one will have additional characters from the first line when adding the second, since I do not overwrite them.

+4
source share
4 answers

If you want to zero out the whole array, you can:

 memset(word, 0, sizeof(word)); 
+15
source

You do not need to clear them if you use strings with a null character in C style. You only need to set the element after the final character in the string to NUL ('\ 0').

For instance,

  char buffer [30] = {'H', 'i', '', 'T', 'h', 'e', ​​'r', 'e', ​​0};
 // or, similarly:
 // char buffer [30] = "Hi There";  // either example will work here.

 printf ("% s", buffer);
 buffer [2] = '\ 0';
 printf ("% s", buffer)

displays

Hi there
Hi

although it is true that buffer[3] == 'T' .

+12
source

strcpy(word,"") can also be used for this purpose.

+3
source

*word = '\0';

Additional materials to go through the 15-digit listing are eye-catching.

0
source

All Articles