Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to quickly zero out an array?

Tags:

arrays

c#

memory

I am currently doing it in a for loop, and I know in C there is the ZeroMemory API, however that doesn't seem to be available in C#. Nor does the somewhat equivalent Array.fill from Java exist either. I am just wondering if there is an easier/faster way?

like image 382
esac Avatar asked Sep 10 '09 21:09

esac


People also ask

How do you zero out an array?

An array is initialized to 0 if the initializer list is empty or 0 is specified in the initializer list. The declaration is as given below: int number[5] = { }; int number[5] = { 0 }; The most simple technique to initialize an array is to loop through all the elements and set them as 0 .

How do you set an int array to zero?

int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index. The array will be initialized to 0 in case we provide empty initializer list or just specify 0 in the initializer list. Designated Initializer: This initializer is used when we want to initialize a range with the same value.

How do I clear an array in C?

Use the memset Function to Clear Char Array in Ch> header file. memset takes three arguments - the first is the void pointer to the memory region, the second argument is the constant byte value, and the last one denotes the number of bytes to be filled at the given memory address.


2 Answers

Try Array.Clear():

Sets a range of elements in the Array to zero, to false, or to null (Nothing in Visual Basic), depending on the element type.

like image 134
Jason Punyon Avatar answered Sep 20 '22 09:09

Jason Punyon


  • C++: memset(array, 0, array_length_in_bytes);

  • C++11: array.fill(0);

  • C#: Array.Clear(array, startingIndex, length);

  • Java: Arrays.fill(array, value);

like image 43
Chap Avatar answered Sep 21 '22 09:09

Chap