9

I use a string:

char    word[100];

I add some chars to each position starting at 0. But then I need be able to clear all those positions so that I can start add new characters starting at 0.

If I don't do that then if the second string is shorten then the first one I end up having extra characters from the first string when adding the second one since I don't overwrite them.

goe
  • 5,207
  • 14
  • 45
  • 49
  • As emerges below, the poster wants to zero out the whole array because he/she doesn't want to use standard library string functions like strcat. He/she wants to be able to just write new chars on top of whatever is there, and count on having a \0 in the next position after he/she stopped writing. – dubiousjim Apr 03 '10 at 17:23

4 Answers4

23

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

memset(word, 0, sizeof(word));
Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
  • @goe could you show us the entire code - or what it actually outputs after you try this? – poundifdef Nov 15 '09 at 02:57
  • 1
    Just want to remind readers that `sizeof(word)` only works as expected when `word` is an array. If `word` is a pointer, then some other way to track the array size is needed. – HAL9000 Jul 31 '21 at 13:07
12

You don't need to clear them if you are using C-style zero-terminated strings. You only need to set the element after the final character in the string to NUL ('\0').

For example,

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)

will output

Hi There
Hi

even though it is still true that buffer[3] == 'T'.

Heath Hunnicutt
  • 18,667
  • 3
  • 39
  • 62
  • I don't care what it will output, I need to rest all of these positions to ''. How can i do that? – goe Nov 15 '09 at 01:20
  • Are you SURE you need to? Because what I am saying is that when programming in C, you normally never need to do that. – Heath Hunnicutt Nov 15 '09 at 01:45
4

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

Sankumarsingh
  • 9,889
  • 11
  • 50
  • 74
1

You could assign a null terminator to the first position of the char array.

*word = '\0';
cigien
  • 57,834
  • 11
  • 73
  • 112
  • 1
    This won't work. When re-filling the array, the \0 gets overwritten and the junk that was there before is still there. – foraidt Nov 14 '09 at 23:09
  • I mis-understood the problem. It is not apparent in the OP that the C string handling functions are not being used. –  Nov 15 '09 at 23:33