If you're using the array to hold strings, you can simply set the first element to the null terminator:
my_array[0]=0;
If you really want to destroy all data in the array, you can use memset():
memset(my_array,0,sizeof my_array);
This can get expensive though if ARR_LEN is a large quantity and/or you're iterating a lot. Probably the first method is what you want.
Russ
bobbitts@hotmail.com
Note : if you are doing the program based on the '\0' then noneed to clear the array. The new string will store the '\0' in the array and it is problem freee.
There is a trik with memset.
In reference said that you can set any value from -255 to 255 for each byte. So you can do it only for char array. For any non char array you can set only "0", because if you put 0 in all 4 integer bytes you still have a zero and "-1",
because it has all 1 in all bits and it will do the same thing with integer - put all 1 in all for bytes and your integer array will be initialize by "-1".
Also you can use memset() for multidimensional arrays, for example:
int a [3][3][3];
memset (&a[0][0][0], 0, 27 * sizeof (int)); or
memset (&a[0][0][0], -1, 27 * sizeof (int));
Hey,
I think memset is better coz u can use it for multi dimensional arrays too. imagine reinitialising using a loop for a multidimensional array. its goin to be hectic.
so go for memset.
Thanx
LOL
to cyberson: the memset and the loop are very closely like solutions. The actually difference, is that memset
usually is optimized with assembly, and/or loop unrolling techniques, but a simplistic, not ansi-correct, not bad-arg passing proof, implementation would be:
void memset(void *x, int c, int n) {
char *z = x;
while (n--) *z++ = c;
}
the idea to get is: to work with a multidimensional array, just cast the base pointer into a char * pointer, and run through the char * pointer for the total length of the multidimensional array.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.