How do I clear a 2D or 3D array fast without loops ?

Nov 20, 2011 at 3:10pm
Hello all!
I can clear a 1D array fast like this:
1
2
char a[10] = "";
int b[5] = {0};


But I don't know how to clear a 2D or 3D array fast without loops:
(I don't want to use a for-loop or while-loop...)
1
2
3
4
5
char a2D[10][5];
int b2D[5][5];

char a3D[10][5][5];
int b3D[5][5][5];
Last edited on Nov 20, 2011 at 6:18pm
Nov 20, 2011 at 3:56pm
1
2
3
4
5
6
7
8
char a2D[10][5];
memset(a2D, 0, 50);

int b2D[5][5];
memset(b2D, 0, 25*(sizeof(int));

int b3D[5][5][5];
memset(b3D, 0, 125*(sizeof(int));
Last edited on Nov 20, 2011 at 3:57pm
Nov 20, 2011 at 4:08pm
Or...

1
2
3
4
5
6
7
8
char a2D[10][5];
memset(a2D, 0, sizeof(a2D));

int b2D[5][5];
memset(a2D, 0, sizeof(b2D));

int b3D[5][5][5];
memset(b3D, 0, sizeof(b3D));


Though the following also work for declaration

1
2
3
4
5
char a2D[10][5] = {0};

int b2D[5][5] = {0};

int b3D[5][5][5]= {0};


But you still need the memset approach to reset the arrays back to zero.

Andy

PS (The following definitely holds for vc++, as is prob true for other compilers) If you set a breakpoint on a line like int b2D[5][5] = {0}; and look at the disassembly, you'll find it's calling memset in most cases. The exceptions seem to be very small structs, like class Point(int x; int y;}; where it just sets the two values to zero. So there's no performance difference between the two approaches for non-tiny arrays.
Last edited on Nov 20, 2011 at 4:41pm
Nov 21, 2011 at 10:30am
Thank you, Moschops!!!
Thank you, andywestken!!!
Topic archived. No new replies allowed.