# Quick way to clear a char array

## Recommended Posts

Chett2001    126
Hey all, im looking for a quick example of how to delete all the information stored in an array so i can put new data into it, and if its smaller not still have data from the previous set. the array is: myPage.pageArray[400][10000] from page class: char pageArray[400][10000]; thanks.

##### Share on other sites
Pzc    216
Do you want something complicated ? Won't just a simple

for( int i = 0 ; i < 400 ; ++i){  for( int j = 0 ; j < 10000 ; ++j )  {    myPage.pageArray[i][j] = 0;   // Assuming that 0 is empty  }}

do the trick ? (Assuming c/c++)

##### Share on other sites
The fastest way to handle that kind of operation is to memset() the memory:

memset(&myPage.pageArray[0][0], 0, sizeof(myPage.pageArray));

Pzc's solution will end up being slower than this (for various reasons).

A similar C++ way would be to use std::fill

char *begin = myPage.pageArray[0][0];
char *end = begin + sizeof(myPage.pageArray);
std::fill(begin, end, 0);

It might be slower than memcpy (although this might not be the case. You'll have to profile...).

Regards,

##### Share on other sites
Antheus    2409
<zen>The fastest way to clear an array is not clearing an array.</zen>

struct Row{  int count;  char entries[10000];};struct Page{  int count;  Row entries[400];};

Now, depending on how you populate the data, you first set the appropriate count to 0, then fill in the required elements into entries, then set count to the number of elements added.

YMMV, but since you have stated that you may have partial data, I'll assume that you're populating each row individually.

C/C++ solutions are the same, just the syntax of structs would differ.

##### Share on other sites
Chett2001    126
Thanks for all the good advice folks, as allways.

##### Share on other sites
Zahlman    1682
Quote:
 Original post by Chett2001from page class:char pageArray[400][10000];

!!!!
Serious warning bells here.

Are you trying to store text in there? That's not what char[]'s are for. String are represented in C++ using a real string type, std::string.

##### Share on other sites
fitfool    113
One more thing. Im not sure, but i dont think what your doing is the proper way to handle the array of that size. I believe you should dynamicly allocate your array so you dont take up all the memory availible in simple terms.