views:

160

answers:

3

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.

+12  A: 

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
I don't care what it will output, I need to rest all of these positions to ''. How can i do that?
goe
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
+10  A: 

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

memset(word, 0, sizeof(word));
Mehrdad Afshari
This doesn't seem to be working...why?
goe
@goe could you show us the entire code - or what it actually outputs after you try this?
rascher
It does work now, I was calling it wrong, thanks
goe
A: 

*word = '\0';

(extra stuff to get past the 15 character posting limit rolls eyes)

Blank Xavier
This won't work. When re-filling the array, the \0 gets overwritten and the junk that was there before is still there.
mxp
This doesn't work either
goe
I mis-understood the problem. It is not apparent in the OP that the C string handling functions are not being used.
Blank Xavier