Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset C int array to zero : the fastest way?

Tags:

c++

arrays

c

memset

Assuming that we have a T myarray[100] with T = int, unsigned int, long long int or unsigned long long int, what is the fastest way to reset all its content to zero (not only for initialization but to reset the content several times in my program)? Maybe with memset?

Same question for a dynamic array like T *myarray = new T[100].

like image 395
Vincent Avatar asked Feb 05 '12 02:02

Vincent


People also ask

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.

How do you clear an int array?

If the elements in the array are no longer desired and what you want is an empty array (i.e., an array with zero elements) ready to be used again then you can use myArray. clear(); or myArray = new ArrayList(); .


1 Answers

memset (from <string.h>) is probably the fastest standard way, since it's usually a routine written directly in assembly and optimized by hand.

memset(myarray, 0, sizeof(myarray)); // for automatically-allocated arrays memset(myarray, 0, N*sizeof(*myarray)); // for heap-allocated arrays, where N is the number of elements 

By the way, in C++ the idiomatic way would be to use std::fill (from <algorithm>):

std::fill(myarray, myarray+N, 0); 

which may be optimized automatically into a memset; I'm quite sure that it will work as fast as memset for ints, while it may perform slightly worse for smaller types if the optimizer isn't smart enough. Still, when in doubt, profile.

like image 191
Matteo Italia Avatar answered Oct 09 '22 13:10

Matteo Italia