Question

I have a loop that populates "char array_of_strings[100][100];" At some point I want to be able to clean it from all the strings added so far and start adding from position 0. How can I clean/rest it in C?

Thanks

Was it helpful?

Solution

Assuming that you are in fact using the array as strings, then something like this should work:

int i;
for (i=0; i<100; i++)
   array_of_strings[i][0] = 0;

Of course, it you aren't treating your data as strings, then you might need to look at something like memset.

OTHER TIPS

You can use the memset function to set all characters back to zero.

P.S. Using a two-dimensional array is fairly unconventional for dealing with strings. Try moving towards dynamic allocation of individual strings.

That data structure really has no inherent structure. You basically reset it by pretending there's nothing in it.

You have some counter that tells you which of the strings you've populated, right? Set it to zero. Done.

memset(array_of_strings, 0, sizeof(array_of_strings));

This is cleaner than putting a magic number for the size in there, and less likely to break down the road when someone changes the size of your strings array. Since you know the size of the array at compile time using sizeof will work.

You can also use bzero, which is a lot like memset, but only for zeroing. On some platforms bzero may be faster than memset, but honestly both functions are so fast, splitting hairs here is silly.

bzero(array_of_strings, sizeof(array_of_strings));

bzero requires you to #include memset needs #include

The memset man page is here

The bzero man page is here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top