Initialize Array

  • Thread starter Thread starter MAF
  • Start date Start date
M

MAF

Is there a quick way to initialize an array with one value

for example

int[] IDs = new int[100];

I want all items to be initialized to -1.
 
MAF,

You could just use a quick loop to do this:

// Initialize all elements to -1.
for (int index = 0; index < IDs.Length; ++index)
{
// Initialize.
IDs[index] = -1;
}

You might be able to get some faster performance by manipulating the
memory directly. If you want, you can use an unsafe block of code and pin
the address of the array. Once you have that, you can pass that to the
RtlFillMemory API function, specifying a value of 255 (you want this because
you want all the bits in the byte to be filled, when you have four bytes
where all the bits are filled, for an int, you have -1).

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top