Here is my code.
DWORD *dwDSE = new DWORD[4096];
Here is my [inefficient] way of clearing it:
for (INT k=0;k<4096;k++)
dwDSE[k] = 0;
What is the best way to clear it/initialize it to zeros?
Here is my code.
DWORD *dwDSE = new DWORD[4096];
Here is my [inefficient] way of clearing it:
for (INT k=0;k<4096;k++)
dwDSE[k] = 0;
What is the best way to clear it/initialize it to zeros?
You can initialized it to zero as
DWORD *dwDSE = new DWORD[4096](); //Note the empty parenthesis ()
Unless you've got a really bad compiler, the most efficient way of clearing it should be:
std::fill_n( dwDSI, 4096, 0 );
This should generate about the same code as your loop (which is
also very efficient), and in many cases, will be significantly
more efficient than memset
, which is normally the worst
solution (and of course, only works for the special value of 0).
Of course, you wouldn't normally ever do a new DWORD[4096]
anyway. If you write:
std::vector<DWORD> dwDSI( 4096 );
you'll get it already initialized to 0, and you won't leak it in
case of an exception. If you need it for a legacy interface
(about the only reason one would use DWORD
anyway), you can
get the raw pointer with &dwDSI[0]
, or dwDSI.data()
if you
have C++11.
EDIT:
A comment to another answer makes me realize an essential point: do you really have to allocate the array dynamically? If not,
DWORD dwDSI[4096] = {};
is the best solution. (The = {}
ensures initialization with
0.)
The memset function can be used in this case.
std::memset(dwDSE, 0, sizeof(dwDSE)*4096);
Or fill_n function:
std::fill_n(dwDSE, 4096, 0);